Python timeit() – Measuring Execution Time with Practical Examples
What is Python timeit()?
Python timeit() is a built‑in module designed to measure the execution time of small code snippets with high precision. By default it runs the statement one million times and reports the fastest run, which helps you compare performance of different implementations.
Syntax
timeit.timeit(stmt, setup, timer, number)
Parameters
- stmt – The code to time. Default is
pass. - setup – Code that runs once before
stmt. Default ispass. - timer – Optional timer function. The module supplies a suitable default.
- number – How many times
stmtis executed. Default is 1 000 000.
Import the module first:
import timeit
Example 1 – Timing a Simple Expression
# Test a basic arithmetic operation import timeit print(timeit.timeit("output = 10*5"))
Typical output:
0.06127880399999999
This shows the time (in seconds) taken for the fastest of one million runs.
Timing Multiple Lines
timeit can handle multi‑line code by separating statements with semicolons or by passing a triple‑quoted string.
Using Semicolons
import timeit
print("The time taken is ", timeit.timeit(stmt="a=10;b=10;sum=a+b"))
Output:
The time taken is 0.137031482
Using Triple‑Quoted Strings
import timeit
import_module = "import random"
testcode = '''
def test():
return random.randint(10, 100)
'''
print(timeit.repeat(stmt=testcode, setup=import_module))
Output:
C:\pythontest>python testtimeit.py The time taken is 0.182619178
Key Methods
- timeit.default_timer() – Returns the current time with the best available resolution.
- timeit.repeat(stmt, setup, timer, repeat, number) – Runs
timeit()repeatedly, returning a list of best times for each run.
Example 1 – Using timeit.timeit()
# Test a function that returns a random integer
import timeit
import_module = "import random"
testcode = '''
def test():
return random.randint(10, 100)
'''
print(timeit.timeit(stmt=testcode, setup=import_module))
Output:
0.46715912400000004
Example 2 – Using default_timer()
# Measure a single function call
import timeit
import random
def test():
return random.randint(10, 100)
starttime = timeit.default_timer()
print("The start time is :", starttime)
test()
print("The time difference is :", timeit.default_timer() - starttime)
Output:
The start time is : 0.220261875 The time difference is : 0.0004737320000000045
Example 3 – Using timeit.repeat()
# Run the test five times and capture the best times
import timeit
import_module = "import random"
testcode = '''
def test():
return random.randint(10, 100)
'''
print(timeit.repeat(stmt=testcode, setup=import_module, repeat=5))
Output:
[0.43638873, 0.5040939680000001, 0.5069179909999999, 0.3943449330000002, 0.3546886979999999]
Each entry is the best time for one iteration of the 1 000 000 runs.
Command‑Line Usage
You can invoke timeit directly from the shell:
python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [code statement ...]
-n N– Number of loops for the statement.-r N– How many times the entire timing process repeats.-s S– Setup code executed once before timing.-t– Usetime.time()as the timer.-c– Usetime.clock()as the timer.-h– Show help.
Example
C:\pythontest>python -m timeit -s 'text="hello world"' 20000000 loops, best of 5: 13.1 nsec per loop
Another convenient way is to call timeit from the REPL:
import timeit
print("The time taken is ", timeit.timeit(stmt="a=10;b=10;sum=a+b"))
Output:
The time taken is 0.15048536300000137
Why timeit() is the Best Tool for Timing Python Code
- It runs the statement many times (default 1 000 000) and returns the fastest run, giving a reliable estimate.
- Garbage collection is disabled during timing, preventing it from skewing results.
- It automatically selects the most precise timer for your operating system (e.g.,
time.clock()on Windows,time.time()on macOS/Linux).
Summary
The timeit module is essential for benchmarking short Python snippets. Its parameters are straightforward:
- stmt – Code to time.
- setup – One‑time setup code.
- timer – Optional timer function.
- number – How many times
stmtruns.
Make sure to use timeit for accurate, repeatable measurements.
Python
- Python Print() Function: A Practical Guide with Examples
- Master Python’s str.count(): How to Count Characters & Substrings with Examples
- Master Python `format()` Strings with Clear Examples
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- Master Python Lambda Functions: Practical Examples & Best Practices
- Python round() Function Explained with Practical Examples
- Mastering Python's map() Function: Syntax, Examples, and Best Practices
- Python list.count(): Expert Guide with Practical Examples
- Mastering Python’s datetime Module: Dates, Times, Timedelta & Strftime Explained
- Python Module Importing – A Practical Guide with Examples