Python timeit

In this post, we will see how to use timeit module to measure execution of small piece of code.
If you want to know how much time it takes to execute any piece of code in python, you can use timeit module.
Let’s say you think that some code is slowing down performance of the program, you can use timeit module to measure time of execution of that code.
The timeit function timeit.timeit(stmt, setup, timer, number) accepts four arguments:

stmt which is the statement you want to measure; it defaults to ‘pass’.
setup: This is the code which you want to run before execution of above stmt ; it defaults to ‘pass’.It generally include import statement.
timer: which a timeit.Timer object; You don’t have to worry about it as it is set to appropriate defautls.
number: which is the number of times you want to executes the stmt.
Where the timeit.timeit() function returns the number of seconds it took to run the code.


Testing time execution of single statement

Let’s understand with the help of example.

import timeit print(timeit.timeit('[n**2 for n in range(100)]', number=10000))

Output:

0.4096612360008294

It means when you executed statement “[n**2 for n in range(100)]” 10000 times and it took 0.4096612360008294 to execute.


Testing time execution of function

You can also check time execution of a function.You need to pass stmt,setup, timer and number as required.
Let me give a simple example to test isPrime function as below.

import timeit def isPrime(num): for i in range(2,int(num**0.5)): if(num%i==0): return False return True SETUP_CODE='''from __main__ import isPrime from random import randint''' TEST_CODE = '''randomNum = randint(0, 10000) isPrime(randomNum)''' # timeit.timeit statement time = timeit.timeit(stmt = TEST_CODE,setup=SETUP_CODE, number = 10000) print('Time taken to execute isPrime function 10000 times is',time)

Output:

Time taken to execute isPrime function 10000 times is 0.04178136100017582

That’s all about Python timeit module

Leave a Reply

Your email address will not be published. Required fields are marked *