The Python timeit module is specially designed to find out the precise execution time of a code snippet. Here in this Python tutorial, we will walk you through how to use the built-in Python library timeit with the help of some examples. timeit is an inbuilt Python module that can evaluate the execution time of a code snippet or program. Although Python also has a datetime module, where we can use its time method before and after a code snippet and find the execution time of the code, this approach is not precise as there are many other background processes that can distort the results.
Python timeit.timeit() Function
timeit()
is a method of the Python timeit module, and it returns the execution time of the code snippet in seconds. The
timeit()
method accepts the Python code snippet in a string and executes it 1 million times, and returns the total execution time by executing the code snippet 1 million times. It is the default number of executions that you can also change if you want.
Python timeit() method syntax:
timeit.timeit(stmt, setup, timer, number)
timeit() Method Parameters
stmt | It is the Python code in the string for which you want to calculate the execution time. The default value of stmt is “pass.” |
setup | It is also a string formatted Python code that executes before the stmt code. setup is generally used to define the import modules. Its default value is also “pass.” |
timer | It is a default function of the timeit() method. timer is an optional parameter, and you do not have to specify it. |
number | It defines the number of times the code should execute. The default value of number is 1000000. |
Python timeit() Method Examples
Example 1: Execute the code 1 million times.
import timeit
#code snippet
code = "[i for i in range(199)]"
execution_time = timeit.timeit(stmt = code)
#execution time of code by 1,000,000
print(execution_time, "seconds" )
Output
7.756799300000001 seconds
The above result does not show the execution time of a single code snippet. It shows the execution time of the code 1 million times. Note: The timeit() method returns the time of executing the code 1 million times. To find out the best execution time, divide the output by 1 million, or set the number parameter to 1. Example 2: Execute the code only one time.
import timeit
#code snippet
code = "[i for i in range(199)]"
#execute the code 1 time
execution_time = timeit.timeit(stmt = code, number =1)
print(execution_time, "seconds" )
Output
1.2000000000012001e-05 seconds
Here, you can see that the execution time of the code snippet is less than 1 second, and it is approximately 0 seconds. Example 3: Execution time of a multi-line Python code. By far, we only encountered examples where the code snippet is of a single line. As we also want to find out the execution time of a function or multiple lines of code. Here, we use Python multiple-line string with triple double, or single quotation marks or separate the line with semicolons. Example 3.1 : Use semicolons for multiple lines of code.
import timeit
#code snippet
code = "a= 20;b= 35;c=39;sum= a+b+c "
#execute the code 1000 time
execution_time = timeit.timeit(stmt = code)
print("Total Execution time:",execution_time, "seconds" )
#divide the execution_time with number or 1000000 to findout the best execution time of code
print("Single Execution time:",execution_time/1000000, "seconds")
Output
Total Execution time: 0.17900560000000004 seconds
Single Execution time: 1.7900560000000004e-07 seconds
Example 3.2 : Use a multi-line string for multiple lines of code.
import timeit
#code snippet
code ="""
def sum(a,b,c):
return a+b+c
"""
#execute the code 100000 times
execution_time = timeit.timeit(stmt = code)\
print("Total Execution time:",execution_time, "seconds" )
#divide the execution_time with number or 1000000 to find out the best execution time of code
print("Single Execution time:",execution_time/1000000, "seconds")
Output
Total Execution time: 0.09432300000000005 seconds
Single Execution time: 9.432300000000004e-08 seconds
Example 4: Measure the time of executing a function using the setup parameter. By far, we have discussed the stmt and number parameters. Let’s also use the setup parameter. The setup parameter is used to specify a code that should execute before every stmt .
import timeit
#setup code
import_math = "import math"
#code snippet
code ="""
def sum(a,b,c):
return (math.sqrt(a) + math.sqrt(b) + math.sqrt(c))**2
"""
#execute the code 200000 times
execution_time = timeit.timeit(stmt = code, setup= import_math, number =2000000)
print("Total Execution time:",execution_time, "seconds" )
#divide the execution_time with number or 1000000 to find out the best execution time of code
print("Single Execution time:",execution_time/2000000, "seconds")
Output
Total Execution time: 0.2599065 seconds
Single Execution time: 1.2995324999999998e-07 seconds
Python Timeit default_timer() Method
The timeit.default_timer() method returns the time when it is executed. It can also be used to find out the execution time of a Python code snippet. Timeit default_timer() Examples Example 1:
import timeit
def test_func():
return [i for i in range(100)]
first_timer =timeit.default_timer()
print(" Statemet1 Executed at:",first_timer , "sec")
test_func()
second_timer = timeit.default_timer()
print("Statemet2 Executed at:", second_timer, "sec")
print("The execution time of test_func() is:", second_timer - first_timer)
Output
Statemet1 Executed at: 0.3830903 sec
Statemet2 Executed at: 0.394941 sec
The execution time of test_func() is: 0.011850699999999992
Example 2: Delay the code execution with the Python time.sleep() method
import time
import timeit
first_timer =timeit.default_timer()
print(" Statemet1 Executed at:",first_timer , "sec")
#2 seconds delay
time.sleep(2)
second_timer = timeit.default_timer()
print("Statemet2 Executed at:", second_timer, "sec")
Output
Statemet1 Executed at: 0.376851 sec
Statemet2 Executed at: 2.4023813 sec
Python Timeit repeat() method
The
timeit
module has the
repeat()
method, which is similar to the
timeit()
method. However, it accepts an additional parameter called
repeat
. The
repeat()
method calls the
timeit()
method the number of times the repeat parameter is specified.
Python timeit repeat() method syntax
repeat(stmt, setup, timer, number, repeat)
Example
import timeit
code="""
def test_func():
return [i for i in range(100)]
"""
#call the timeit() method 4 times
print(timeit.repeat(stmt=code, repeat=4))
Output
[0.14668000000000003, 0.11089179999999998, 0.0876074, 0.09344799999999998]
Timeit Command Line tool
The Python
timeit
module also provides a command-line interface to find out the execution time of a Python code snippet directly from the command prompt or terminal.
Timeit Command Line syntax
python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...]
- [-n Number] represents the number of times the code statement should execute.
- [-r Number] represents the number of times the timer should repeat. The default value is 5.
- [-s String] represents the setup parameter that will execute once before the code statement.
- [-u Unit] represents the unit of timer, namely nsec, usec, msec or sec.
- [-h] displays the help message.
- [statemet…] represents the code snippet.
Python Timeit Command Line Tool Example
Example 1
C:\Users\tsmehra>python -m timeit "[i for i in range(200)]"
50000 loops, best of 5: 4.86 usec per loop
Example 2
C:\Users\tsmehra>python -m timeit -n 100 "[i for i in range(200)]"
100 loops, best of 5: 4.87 usec per loop
Example3
C:\Users\tsmehra>python -m timeit -n 100 -r 10 "[i for i in range(200)]"
100 loops, best of 10: 4.84 usec per loop
Example 4
C:\Users\tsmehra>python -m timeit -n 100 -r 10 -u sec "[i for i in range(200)]"
100 loops, best of 10: 4.69e-06 sec per loop
Summary
In this program, we saw many examples of the Python timeit() module. timeit is an inbuilt Python module that can calculate the execution time of a Python code snippet. The timeit module has three major methods, namely timeit(), default_timer(), and repeat(), which can calculate the code execution time. The Python
timeit()
method accepts the code as a string and returns the execution time in seconds. On the contrary, the
default_timer()
method returns the time of its execution. The
repeat()
method calls the
timeit()
method a number of specified times.
People are also reading:
Leave a Comment on this Post