What is Python Timeit?

Python Timeit is a method in the Python library to measure the execution time taken by the given code fragment. The Python library runs the code several times(1 million times) and provides the minimum time taken from the given piece of code.

It is a useful method that helps us in checking the code performance.

Why Python Timeit is best to measure the execution time of code?

It runs the code 1 million times, that is the default value, and it will return you the minimum time taken. During execution, the garbage collection is disabled every time by the time() function.

Timeit will use time.clock() for Windows operating system and time.time() for mac and Linux for taking the accurate time.

Basic Syntax & Parameters of itmeit Python & How to use it?

To use the timeit() method, we need to import the module as shown below,

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

The different parameters are-

  • stmt :- It takes the code for which you want to measure the execution time. The default value is “pass”.
  • setup :- It has the setup details that need to be executed before stmt. The default value is “pass”.
  • timer :- It contains the timer value, timeit() already has a default value set.
  • number :- The stmt executes as per the number given here. The default value is 1000000.

Example:

import timeit
def test(n):
    return sum(range(n))
n = 10000
loop = 1000
result = timeit.timeit('test(n)', globals=globals(), number=loop)
print(result / loop)

As a result, the output will be:
0.0002666301020071842

A simple test(n) function calculating the sum of n consecutive numbers is used here, and its execution time is measured. We are measuring the timeit.timeit() as a string. The piece of code is executed n times and the execution time is returned.

Note: Since the default value of the number is 1000000, it will take a lot of time to run the code that much.

Multiple lines for code execution

We can execute multiple lines of code in timeit.timeit(), using a semicolon using triple quotes.
Case 1(Using semicolon):

import timeit
print("Time taken is ", timeit.timeit(stmt='a=20;b=20;sum=a+b'))

As a result, the output is:
Time taken is 0.0592726

Case 2(Using triple quotes):

import timeit
import_module = "import random"
testcode = ''' 
def test(): 
    return random.randint(10, 100)
'''
print(timeit.repeat(stmt=testcode, setup=import_module))

As a result, the output is:
[0.055116399999999996, 0.0550703, 0.054926400000000014, 0.0535611, 0.05349079999999995]

Python Lambda Expression

A piece of code can be an object instead of a string, so it can be specified using a lambda expression with no arguments. Here, the argument(global) is not specified.

result = timeit.timeit(lambda: test(n), number=loop)
print(result / loop)

As a result, the out is:
0.00027574066299712287
Therefore, the timeit.timeit() gives us the time(in seconds) it takes to execute the code n times. The time per execution is measured by dividing it by the number of executions(n).

Note: If we don’t divide, the resultant value will become larger as we increase the number of executions.

Methods in Python Timeit

Timeit in Python has two very important methods- timeit.default_timer() and timeit.repeat(stmt, setup, timer, repeat, number).
timeit.default_timer() : Returns the default time when executed.
timeit.repeat(stmt, setup, timer, repeat, number) : Works same as timeit(), but with repeat the timeit() is called the number of times repeat is given.

Example 1(timeit.default_timer()):

import timeit
import random


def test():
    return random.randint(10, 100)


start_time = timeit.default_timer()
print("The start time is :", start_time)
test()
print("The time difference is :", timeit.default_timer() - start_time)

As a result, the output is:
The start time is : 0.0424369
The time difference is : 6.450000000000206e-05

Example 2(timeit.repeat()):

import timeit
import_module = "import random"
test_code = ''' 
def test(): 
    return random.randint(10, 100)
'''
print(timeit.repeat(stmt=test_code, setup=import_module, repeat=4))

As a result, the output is:
[0.08312800000000001, 0.0651274, 0.060115999999999975, 0.0637141]

Pyhton Timeit in Command Line

When it is called from the command line, the following form is used:

python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement...]

here the terms are,
-n N :- number of times to execute ‘statement’.
-r N :- number of times to repeat timer(default is 5).
-u U :- unit for timer output(nano, micro, mil, sec).
-s S :- setup statement to be executed.
-h :- prints a short use message(help).

Example:
>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.41440500499993504
>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
1.7246671520006203

Conclusion

Python Timeit is a useful library. However, we should be aware of some of its drawbacks too. It should be avoided for whole-program profiling.

There are better means out there for this case, like Python’s cProfile module, generating far more detailed statistics about the entire program’s performance.

Timeit works best with a few lines of code.

Moreover, modern programmes don’t run at the same speed every time.

We should run a timeit code many times, pick out the worst and best scores, and work out the average. In conclusion, it also helps to run the same test on different systems.

You can also learn about How to use Pyhton Average

Like this article? Follow us on Facebook and LinkedIn.