timeit | Python Standard Library – Real Python
The Python timeit module provides tools to measure the execution time of small code snippets. It’s useful for performance testing and benchmarking.
Here’s a quick example:
Key Features
- Measures the execution time of small code snippets
- Provides repeatable and accurate timing results
- Supports setup code for benchmarking context
- Minimizes external influences for precise measurements
- Works from the command line or within Python scripts
- Enables micro-benchmarking for performance-critical code
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
timeit.timeit() |
Function | Times the execution of a single statement |
timeit.repeat() |
Function | Repeatedly times the execution to get multiple samples |
timeit.Timer |
Class | Provides a class-based interface for timing code |
Examples
Measure the execution time of a code snippet:
Use repeat() to get multiple timing samples:
Common Use Cases
- Measuring the execution time of small code snippets
- Comparing the performance of different code implementations
- Optimizing code by identifying bottlenecks
- Validating the impact of refactoring or optimization
- Evaluating standard vs third-party implementation speed
- Timing examples in tutorials or documentation
Real-World Example
Say that you want to compare the performance of two different ways to create a list of squares:
In this example, you time two approaches for creating a list of squares. The results show that squares_1(), which uses a list comprehension, is faster than squares_2(), which uses map() and a lambda function.
For additional information on related topics, take a look at the following resources: