How to Use the Python Timeit Module

09/18/2021

Contents

In this article, you will learn how to use the Python timeit module.

Python Timeit Module

The Python timeit module is a built-in library that is designed to measure the execution time of small code snippets. It provides a simple and reliable way to benchmark your Python code and compare the performance of different implementations.

Here are the basic steps for using the timeit module in Python:

Import the timeit module:

import timeit

Define the code that you want to benchmark as a string or a function:

code_to_test = """
your code here
"""

Alternatively, you can define a function that encapsulates the code you want to test:

def my_function():
    your code here

Use the timeit module to measure the execution time of your code:

# measure the execution time of a code snippet
timeit.timeit(code_to_test)

# measure the execution time of a function call
timeit.timeit(my_function)

Optionally, you can specify the number of times you want to run the code by passing the number parameter:

timeit.timeit(code_to_test, number=1000)

This will run the code 1000 times and return the total execution time.

Finally, you can print the result to see the execution time:

print(timeit.timeit(code_to_test))

This will print the execution time in seconds.

Here’s an example of using the timeit module to measure the execution time of a simple code snippet:

import timeit

code_to_test = """
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in my_list:
    print(i)
"""

execution_time = timeit.timeit(code_to_test)
print(execution_time)

This code will output the execution time of the code snippet in seconds.