Python Timeit() with Examples

By | September 27, 2021
Python Timeit() with Examples

Python comes with an in-built module timeit, 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. But this approach is not precise and there are many other background processes which can distort the result.

The Python timeit() module is specially designed to find out the precise execution time of a code snippet. And here in this Python tutorial we will walk through how to use Python in-built library timeit, with the help of some examples. 

Vamware

Python timeit.timeit() Function:

timeit() is a method of 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 execute it 1 million times. And return the total execution time, by executing the code snippet 1 million times. 1 million times is the default number of executions, you can also change it.

Python timeit() method syntax:

 timeit.timeit(stmt, setup, timer, number)

timeit() method parameters

stmt It is the Python code in the string which execution time you want to calculate.

The default value of stmt is “pass”.

setup It is also a string formatted Python code that executes before the stmt code.

It is generally used to define the import modules.

Its default value is also “pass”

timer It is a default function of timeit() method.

It 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 time.

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, it shows the execution time of 1 million code.  

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 1 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 code is less than 1 second it is approx. to 0 secoond.

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 line code. There we use Python multiple-line string with triple-double or single quotation or separate the line with semicolons.

Example 3.1: Use semicolons for multiple line codes.

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 Multi-line string for multiple line 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 a function execution using 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 the Python code.

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 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 library repeat() method

The timeit module repeat() method is similar to timeit() method. But it accepts an additional parameter called repeat. The repeat() method call the timeit() method the number of times 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 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] It represent the number of times the code statement should execute

[-r Number] It represent the how many times the timer should repeat default value is 5.

[-s String] It represent the setup parameter, that will execute once before the code statement.

[-u Unit] It represent the unit of timer nsec, usec, msec or sec.

[-h] It display the help message

[statemet…] It represent 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

  • Timeit is a Python inbuilt module that can calculate the execution time of Python code.
  • Timeit module has three major methods timeit(), default_timer() and repeat() that can calculate code execution time.
  • The timeit() method accepts the code as a string and returns the execution time in seconds.
  • The default_timer() method returns the time of its execution.
  • The repeat() method call the timeit() method a number of specified times.

People are also reading: 

Leave a Reply

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