How to Use timeit in Python for Measuring Code Execution Time
Use the
timeit module in Python to measure how long a piece of code takes to run by calling timeit.timeit() with the code as a string and the number of repetitions. This helps you check performance by running the code multiple times and getting the average time.Syntax
The basic syntax of timeit.timeit() is:
stmt: The code you want to time, as a string.setup: Code to run once before timing, usually imports or variable setup, as a string.number: How many times to runstmt(default is 1,000,000).
The function returns the total time in seconds to run stmt number times.
python
timeit.timeit(stmt='code_to_test()', setup='from __main__ import code_to_test', number=1000000)
Example
This example measures how long it takes to create a list of squares using a list comprehension versus a for loop.
python
import timeit code_list_comp = '[x*x for x in range(1000)]' code_for_loop = ''' result = [] for x in range(1000): result.append(x*x) ''' # Time list comprehension time_list_comp = timeit.timeit(stmt=code_list_comp, number=1000) # Time for loop time_for_loop = timeit.timeit(stmt=code_for_loop, number=1000) print(f'List comprehension time: {time_list_comp:.5f} seconds') print(f'For loop time: {time_for_loop:.5f} seconds')
Output
List comprehension time: 0.06000 seconds
For loop time: 0.12000 seconds
Common Pitfalls
Common mistakes when using timeit include:
- Not importing functions or variables used in
stmtinsidesetup, causingNameError. - Using multi-line code incorrectly without triple quotes.
- Running
timeiton code with side effects that affect timing. - Not specifying
numberand getting misleading results for very fast or slow code.
Always import or define what your timed code needs in setup and use triple quotes for multi-line statements.
python
import timeit # Wrong: missing import in setup # timeit.timeit(stmt='my_func()', number=1000) # Right: import function in setup # timeit.timeit(stmt='my_func()', setup='from __main__ import my_func', number=1000)
Quick Reference
| Parameter | Description |
|---|---|
| stmt | Code to time, as a string |
| setup | Setup code run once before timing, as a string |
| number | How many times to run stmt (default 1,000,000) |
| repeat | Number of times to repeat timing (use timeit.repeat) |
| Returns | Total time in seconds to run stmt number times |
Key Takeaways
Use timeit.timeit() to measure execution time of small code snippets accurately.
Always include necessary imports or setup code in the setup parameter.
Run the code multiple times with the number parameter for reliable timing.
Use triple quotes for multi-line code in the stmt parameter.
Avoid side effects in timed code to get consistent results.