Python Timeit Module

In this tutorial, we will learn how to use timeit module in Python. In the Python library, there exists a remarkable method called timeit(), designed specifically to gauge the execution time of a given code snippet. This method operates by running the code statement an astonishing one million times, diligently recording the duration for each iteration. Ultimately, it bestows upon us the minimum time taken from this comprehensive set of code snippets. This invaluable tool, timeit(), serves as an indispensable aid in evaluating the performance of our code, allowing us to scrutinize its efficiency with utmost precision.

Python Timeit Module

timeit syntax

timeit.timeit(stmt, setup, timer, number)

Parameters

  • stmt: This parameter represents the code statement or function that we want to measure the execution time for. It can be a string containing the code snippet or a callable object.
  • setup: This parameter is optional and is used to specify any setup code required for the code snippet. It can also be a string or a callable object. If not provided, it defaults to “pass”.
  • timer: This parameter is optional and allows us to choose the timer implementation used for timing the code snippet. By default, it uses a system-specific timer. We can provide our own timer function if desired.
  • number: This parameter is optional and specifies the number of times the code snippet should be executed. The default value is 1 million.

To use timeit method firstly we have to import timeit as below

import timeit

Example 1:

import timeit

code_snippet = """
# Code snippet to measure execution time
for i in range(1000000):
    pass
"""

execution_time = timeit.timeit(stmt=code_snippet, number=10)
print(f"Execution time: {execution_time} seconds")


Output:

Execution time: 0.18201991300156806 seconds

In this example, we measure the execution time of a code snippet that simply iterates one million times using a for loop. The stmt parameter is set to the code snippet, and the number parameter is set to 10, indicating that the snippet will be executed 10 times. The timeit() method returns the total time taken for these 10 executions, which is then printed to the console.

Example 2:

import timeit

code_snippet = """
# Code snippet to measure execution time
for i in range(1000000):
    pass
"""

execution_time = timeit.timeit(stmt=code_snippet, number=10)
print(f"The execution time is {execution_time} seconds.")


Output:

The execution time is 0.078435679 seconds.

In this example, we measure the execution time of a code snippet that iterates one million times using a for loop. The stmt parameter is set to the code snippet, and the number parameter is set to 10, indicating that the snippet will be executed 10 times. The timeit() method returns the total time taken for these 10 executions, which is then printed to the console.

Example 3:

import timeit

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

execution_time = timeit.timeit(stmt=lambda: fibonacci(10), number=1)
print(f"The execution time is {execution_time} seconds.")


Output:

The execution time is 0.133402965 seconds.

In this example, we measure the execution time of the fibonacci() function, which calculates the Fibonacci sequence recursively. The stmt parameter is set to a lambda function that calls fibonacci(10), and the number parameter is set to 1. The timeit() method returns the time taken for this single execution, which is then printed to the console

Different types of timeit methods

There are two important methods available

timeit.default_timer()

The timeit.default_timer() function in Python is a highly convenient tool that provides a timer implementation suitable for measuring the execution time of code snippets. It returns the time in seconds as a floating-point value, allowing for precise timing measurements.

Syntax:

import timeit

start_time = timeit.default_timer()

# Code snippet to measure execution time

end_time = timeit.default_timer()

execution_time = end_time - start_time

To employ timeit.default_timer(), we import the timeit module and call the function twice: once at the beginning of the code snippet we wish to measure and again at the end. By subtracting the start time from the end time, we obtain the execution time in seconds.

Example:

import timeit

start_time = timeit.default_timer()

# Code snippet to measure execution time
for i in range(1000000):
    pass

end_time = timeit.default_timer()

execution_time = end_time - start_time
print(f"Execution time: {execution_time} seconds")


Output:

Execution time: 0.03646230000000001 seconds

In this example, we have a simple code snippet that iterates one million times using a for loop. We capture the start time using timeit.default_timer() before executing the code, and then capture the end time after the code execution. Subtracting the start time from the end time provides us with the execution time, which we print to the console.

timeit.repeat()

The timeit.repeat() method in Python is a powerful tool for measuring the execution time of a code snippet. It allows us to obtain a series of timing results by repeating the measurement multiple times.

Syntax:

import timeit

timeit.repeat(stmt, setup, timer, repeat, number)

The timeit.repeat() method accepts five parameters:

  • stmt: This parameter represents the code statement or function that we want to measure the execution time for. It can be a string containing the code snippet or a callable object.
  • setup: This parameter is optional and is used to specify any setup code required for the code snippet. It can also be a string or a callable object. If not provided, it defaults to “pass”.
  • timer: This parameter is optional and allows us to choose the timer implementation used for timing the code snippet. By default, it uses a system-specific timer. We can provide our own timer function if desired.
  • repeat: This parameter is optional and specifies the number of times the measurement should be repeated. The default value is 5.
  • number: This parameter is optional and specifies the number of times the code snippet should be executed in each measurement. The default value is 1 million.

Example:

import timeit

code_snippet = """
# Code snippet to measure execution time
for i in range(1000000):
    pass
"""

timing_results = timeit.repeat(stmt=code_snippet, repeat=3, number=10)
for i, result in enumerate(timing_results):
    print(f"Measurement {i+1}: {result} seconds")


Output:

Measurement 1: 0.120345 seconds
Measurement 2: 0.121432 seconds
Measurement 3: 0.122815 seconds

In this example, we measure the execution time of a code snippet that iterates one million times using a for loop. The stmt parameter is set to the code snippet, and the repeat parameter is set to 3, indicating that the measurement will be repeated three times. The number parameter is set to 10, meaning the snippet will be executed ten times in each measurement. The timeit.repeat() method returns a list of timing results, which are then printed to the console for each measurement

Why is timeit() the best way to measure the execution time of Python code

The timeit() method in Python is considered one of the best ways to measure the execution time of code for several reasons:

  • Accurate Timing: timeit() performs precise timing measurements by executing the code snippet multiple times and calculating the minimum execution time. This approach helps eliminate potential variations caused by external factors like system load or background processes, providing reliable and accurate timing information.
  • Repeatable Results: By default, timeit() executes the code snippet one million times, ensuring a sufficiently large sample size for timing measurements. This repetition helps in minimizing the impact of small variances and provides consistent results across multiple runs.
  • Built-in Timer: The timeit() method utilizes a timer implementation optimized for timing code execution. It employs a high-resolution timer, specific to the underlying operating system, to achieve precise and platform-independent timing measurements.
  • Flexible Setup: timeit() allows you to specify the setup code alongside the code snippet being timed. This feature is particularly useful when your code requires initialization or additional setup steps before execution. By separating the setup code from the timed portion, you can accurately measure the execution time of the primary logic.
  • Easy to Use: The timeit() method is straightforward to implement. With a minimal amount of code, you can accurately measure the execution time of your Python code. It provides a convenient way to evaluate and compare different approaches, optimizations, or algorithms to identify the most efficient solution.

Conclusion

Overall, the timeit() method is a reliable and widely used tool for measuring the execution time of Python code. Its accuracy, repeatability, built-in timer, flexibility, and ease of use make it the preferred choice for performance analysis and optimization tasks.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!