Python Timeit() with Examples

Python's timeit module provides a way to measure the execution time of small code snippets . It can be used to determine the execution time of a single line of code or an entire function.


Syntax:
import timeit timeit.timeit(stmt, setup, timer, number)
  1. stmt: This is the statement to be timed. It can be a single line of code or a multi-line code block.
  2. setup: This is a setup statement that is executed only once before the timed statement. It can be used to import modules or define variables that are used in the timed statement.
  3. timer: This is an optional timer function that can be used to measure the execution time. The default timer function is time.perf_counter.
  4. number: This is the number of times the statement is executed. The default value is number=1.

Following are some examples of how to use timeit:

Timing a single line of code

import timeit # Timing a single line of code print("Execution time : " , timeit.timeit('x = sum(range(100))')) #Output: Execution time : 1.2897200759980478

Above code snippet times the execution of a single line of code that sums the range of numbers from 0 to 99. The timeit.timeit function returns the execution time in seconds.

Timing a function call

import timeit # Define a function def my_function(): x = sum(range(100)) return x # Timing the function call print("Time taken : " , timeit.timeit('my_function()', setup='from __main__ import my_function')) #Output: Time taken : 1.0421477419986331

Above code snippet times the execution of a function call that sums the range of numbers from 0 to 99. The setup parameter is used to import the function into the timer namespace so that it can be called from the timed statement.

Timing a multi-line code block using triple quotes

import timeit # Timing a multi-line code block code_block = """ x = 0 for i in range(100): x += i """ print("Time taken : " , timeit.timeit(code_block)) #Output: Time taken : 3.127869047999411

Above code snippet times the execution of a multi-line code block that sums the range of numbers from 0 to 99. The code block is defined as a string and passed to the timeit.timeit function as the timed statement.

Timing Multiple lines block using semicolon

You can use a semicolon to separate multiple statements on the same line. This can be useful for timing multiple lines of code with the timeit module. Here is an example:

import timeit # Timing multiple lines of code with semicolon print("Time taken : " ,timeit.timeit('x = 0; y = 0; z = 0; x += 1; y += 2; z += 3')) #Output: Time taken : 0.05426340689882636

Above code snippet times the execution of multiple statements separated by semicolons. The timeit.timeit function returns the execution time in seconds.

Note that using semicolons to separate statements on the same line can make the code harder to read and maintain. It's generally better to use separate lines for each statement, especially for longer or more complex code blocks.

Using a custom timer function

import timeit import time # Define a custom timer function def custom_timer(): return time.process_time() # Timing a single line of code with custom timer print("Time taken : ", timeit.timeit('x = sum(range(100))', timer=custom_timer)) #Output: Time taken : 1.0788690060000001

Above code snippet times the execution of a single line of code that sums the range of numbers from 0 to 99. The timer parameter is used to specify a custom timer function that measures CPU time instead of wall-clock time.

Other commonly used functions in timeit


Why Is timeit() the Best Way to Measure the Execution Time of Python Code

The timeit module in Python provides a way to time the execution of small bits of Python code. Here are some commonly used functions in the timeit module along with examples:

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

This function is similar to timeit.timeit(), but it executes the statement multiple times and returns a list of timings for each execution. The repeat parameter specifies the number of times to execute the statement.

Repeating a simple statement:
import timeit t = timeit.repeat('x = 1 + 2', repeat=3) print(t) #Output: [0.025312257930636406, 0.02583220391534269, 0.02512429398484528]
Repeating a function call with setup:
import timeit # repeating a function call with setup setup = 'def square(x): return x*x' stmt = 'y = square(5)' t = timeit.repeat(stmt, setup=setup, repeat=3) print(t) #Output: [0.1265363519996754, 0.1058627250004065, 0.09457351200035191]

timeit.default_timer()

This function returns a timer function that is used by default in timeit.timeit() and timeit.repeat().

import timeit # using the default timer function t1 = timeit.timeit('x = 1 + 2') t2 = timeit.timeit('x = 1 + 2', timer=timeit.default_timer())

timeit.Timer(stmt, setup)

This class provides an alternative way to time a statement. It takes the statement and setup as parameters and provides methods to time the execution.

import timeit # creating a Timer object setup = 'def square(x): return x*x' stmt = 'y = square(5)' timer = timeit.Timer(stmt, setup=setup) # timing the execution t1 = timer.timeit() t2 = timer.repeat(repeat=3, number=1000) print(t1) print(t2)
#Output: 0.07549943499907386 [8.71620031830389e-05, 8.505100049660541e-05, 6.910899901413359e-05]

timeit.Timer(stmt, setup)

timeit.Timer(stmt, setup) is a class in the timeit module that provides an alternative way to time the execution of a statement. It takes two parameters:

  1. stmt (required): The statement to be timed as a string.
  2. setup (optional): The setup code to be executed before the statement as a string. If not provided, an empty string is used.

The Timer object has the following methods to time the execution of the statement:

  1. timeit(number=1000000): This method executes the statement number times and returns the total time taken in seconds.
  2. repeat(repeat=5, number=1000000): This method repeats the timeit method repeat times and returns a list of the timings.

The number parameter specifies the number of times to execute the statement for each timing.

import timeit setup = 'x = 5' stmt = 'y = x*x' # Create a Timer object with the statement and setup timer = timeit.Timer(stmt, setup=setup) # Time the execution of the statement t1 = timer.timeit() print(f'Time taken: {t1} seconds') # Repeat the timing 3 times and return the timings timings = timer.repeat(repeat=3, number=1000000) print(f'Timings: {timings}')
#Output: Time taken: 0.019269513999461196 seconds Timings: [0.029357147999689914, 0.019387773998460034, 0.01931290100037586]

In the above example, the Timer object is created with a simple setup and statement. The timeit method is called on the timer object to time the execution of the statement. The repeat method is called on the timer object to repeat the timing 3 times and return the timings.

timeit.time_per_call(stmt, setup=None, timer=, number=1000000, globals=None)

This function is used to time a single call to the given statement stmt by executing it number times and returning the time taken per call.

timeit.Timer(stmt='pass', setup='pass', timer=, globals=None)

This class provides an alternative way to time a statement. It takes the statement and setup as parameters and provides methods to time the execution.

timeit.default_repeat()

This function returns the default value for the repeat parameter in timeit.repeat(). It is currently set to 5.

timeit.default_number()

This function returns the default value for the number parameter in timeit.timeit() and timeit.repeat(). It is currently set to 1000000.

timeit.disable_gc()

This function disables the garbage collector during timing. It can be used to get more accurate timings for code that creates a lot of garbage.

timeit.enable_gc()

This function enables the garbage collector during timing. It is enabled by default.

timeit.get_ident()

This function returns a unique integer identifier for the current thread.

timeit.Timer.autorange(callback=None)

This method is used to automatically determine the number of iterations to use for timing. It takes an optional callback function that can be used to control the timing process.

These are some of the commonly used functions in the timeit module in Python.