Measure execution time using timeit module

Posted by Afsal on 21-Jan-2022

Today we are going to learn a simple module called timeit. It is used to measure the execution time of small snippets of code. In this tutorial, we are using the two most common methods. They are timeit and repeat. Let's look at them one by one.

timeit

timeit returns the time taken by the code for executing n times. By default, it returns the time taken for 1000000 iteration.The function return the time in seconds

Syntax

timeit.timeit(<statement to run>, number=<no of iterations>)

Example

import timeit

def sum_function_to_test():
    sum = 0
    for i in range(20):
            sum += 1
    return sum

time_taken = timeit.timeit(sum_function_to_test, number=1000)

print("\nTotal time taken: ", time_taken, "\n")

Result:

Total time taken:  0.0007164519993239082

repeat:

This method repeats timeit functionality n times. It will return an array of time taken for each repeat. Repeat functionality will provide you with a clearer picture. The function return the time in seconds

Syntax

timeit.repeat(<statement to run>, number=<number of iteration>, repeat=<number of repeatation>)

Example

import timeit

def sum_function_to_test():
    sum = 0
    for i in range(20):
        sum += 1
    return sum

time_taken = timeit.repeat(sum_function_to_test, number=1000, repeat=3)

print("\nTotal time taken: ", time_taken, "\n")

Output

Total time taken:  [0.0010535529982007574, 0.001018984999973327, 0.000877558999491157]

 

Hope you have understood the functionalities. Please share your valuable suggestions or topic to discuss with afsal@parseltongue.co.in

Happy coding!