As we all know, python has a goldmine of handy libraries. In this article, let’s look at a beneficial method of measuring the execution time of your python code snippets. You guessed it right le. Let’s look at how we can use the Timeit() method. Timeit() is a built-in pythons module that provides a simple way to find the execution time of small bits of Python code. In this article, let’s take a look at you can use timeit().
Installation of timeit
Timeit() module comes built-in with python, so all you need to do is import it.
# importing the required module
import timeit
Python timeit
Timeit() makes it accurate and straightforward to find out the execution time of small code snippets. We can use timeit() in both ways Command-line-interface(cli) or a callable one.
Parameters in timeit()
So , timeit( ) take four arguments which are timeit.timeit(stmt, setup, timer, number).
- stmt will take the code for which you want to measure the execution time. The default value is set to “pass”.
- setup will have setup details that need to be executed before stmt. The default value is set to “pass.”
- timer will have the timer value, timeit() already has a default value set. So , we don’t have to worry about it.
- number will take the number of execution you want to run on smt. The default value is set to 1000000.
Basic Example of timeit Module
Let’s take a look at an example for a better understanding.
import timeit
# code snippet to be executed only once
setup_details = "import random"
# code snippet whose execution time is to be measured
samplecode = '''
def example():
somenumber = random.randit(0,50)
return somenumber
'''
# timeit statement
print ("Execution time of program:-", timeit.timeit(setup = setup_details,
stmt = samplecode,
number = 10000))
Output
Execution time of program:- 0.0017167000000000016
Python timeit() methods
There are two methods present in the timeit( ). The two methods are timeit.default_timer() and timeit.repeat(stmt, setup, timer, repeat, number).
- timeit.default_timer() will provide the best clock available on your platform.
- timeit.repeat(stmt, setup, timer, repeat, number) is similar to the timeit( ) method we used preiously with added feature of repeat which will call the the timeit() the number of times repeat is mentioned.
Let’s better understand these two methods using an example.
Example to Understand Two Methods of Python timeit Module
Example 1:
import timeit #using timeit.default()
start = timeit.default_timer()
for i in range(0,50):
pass
end = timeit.default_timer()
print(end - start)
#Output
6.399999999996
Example 2
import timeit #using timeit.repeat()
setup_details = "import random"
samplecode = '''
def example():
somenumber = random.randit(0,50)
return somenumber
'''
print ("Execution time of program:-", timeit.repeat(setup = setup_details,
stmt = samplecode,repeat=5))
#Output
Execution time of program:- [0.1489412, 0.14861209999999997, 0.15124629999999994, 0.15548090000000003, 0.1436058]
Python timeit() Using Command-line-Interface
As mentioned above, we can also use timeit() in the cli.
python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [code ...]
- -m : this will take the positional argument in our case its timeit
- -n N: will take the number of execution you want to run on code .
- -r N: This allow yo to mention the number of time you want to repeat timeit( ) .
- -s S: This will allow you y=to setup details that need to be executed before code.
- -h: for help.
- code : The code details.
Example to Understand timeit() Using Command-line-Interface
C:\Pythonpool\>python -m timeit -s "from math import sqrt" -n 10000 -r 4 "y = sqrt(12)"
#Output
10000 loops, best of 4: 81.4 nsec per loop
Python time.time Vs timeit.timeit
So, you might be asking why timeit( ) why can’t you use time module to calculate the time taken by code snippet by doing these for example:-
import time
start = time.time()
for i in range(0,6):
print(i)
time.sleep(1)
end = time.time()
print(f"Total runtime of the program is {end - start}")
#Output
0
1
2
3
4
5
Total runtime of the program is 1.0139861106872559
Explanation
Well, you see the problem with using the time module to calculate the execution time of small code snippets is that they are not that accurate because the results produced by time.time may also be affected by some other process that was running in the background in your system at that time.
But the timeit module is great for calculating the execution time of small code snippets because timeit runs your snippet of code 1millions of times (default value is 1000000) and provides the minimum time taken from the given set of code snippets, and it is pretty easy to use.
Is timeit in Jupyter Same as timeit()
Yes, the %timeit magic command in jupyter is similar to the timeit() we discussed here.
Python timeit lambda
You can use timeit() with lambda functions, but it’s not recommended when testing small code snippets since it adds overhead.
import timeit
print(timeit.timeit(lambda: 4 + 5))
print(timeit.timeit("output = 4 + 5"))
#Output
0.10917500000000001
0.02280180000000001
Reasons why timeit() is better
- It repeats the tests many times to eliminate the influence of other background tasks on your machine for example os scheduling.
- It also disables the garbage collector for more precise result.
FAQs on Python timeit
By using str( timeit(….)) we can convert the timeit() return value as string.
Currently, Timer() only supports 4 parameters, namely, stmt, setup, timer, and globals. You can pass all the parameters at one line by using Timer(stmt=’pass’, setup=’pass’, timer=, globals=None). Use arguments that correspond to each of these parameters and initialize the class.
Alternatives to timeit() are the python time module, Timerit extension.
Conclusion
In summary, timeit() is a handy module for finding out the execution time of small code snippets and can be very handy to know.