1 min read

Python Timeit Module

The timeit module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution time.

Importing the Module

import timeit

Basic Usage

timeit.timeit()

The timeit() function runs the setup code once, then executes the statement repeatedly (default 1,000,000 times) and returns the total execution time in seconds.

import timeit

execution_time = timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
print(execution_time)

timeit.repeat()

The repeat() function calls timeit() multiple times and returns a list of results.

import timeit

times = timeit.repeat('"-".join(str(n) for n in range(100))', repeat=3, number=10000)
print(times)

Using Setup Code

You can pass setup code (e.g., imports or variable definitions) to the setup parameter. This code is executed once before the timing loop begins.

import timeit

setup_code = "from math import sqrt"
stmt_code = "sqrt(9)"

print(timeit.timeit(stmt=stmt_code, setup=setup_code, number=100000))

Command Line Interface

You can also use timeit from the command line.

python -m timeit '"-".join(str(n) for n in range(100))'

programming/python/python