timeit

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:

Python
>>> import timeit

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

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:

Python
>>> timeit.timeit("sum(range(100))", number=1000)
0.005625799999999981

Use repeat() to get multiple timing samples:

Python
>>> timeit.repeat("sum(range(100))", repeat=5, number=1000)
[
    0.005487599999999985,
    0.005484900000000004,
    0.005458199999999995,
    0.005459500000000017,
    0.005463200000000028
]

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:

Python
>>> def squares_1():
...     return [x**2 for x in range(1000)]
...

>>> def squares_2():
...     return list(map(lambda x: x**2, range(1000)))
...

>>> timeit.timeit(squares_1, number=10000)
0.6023182999999999
>>> timeit.timeit(squares_2, number=10000)
0.7064311999999999

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.

Tutorial

A Beginner’s Guide to the Python time Module

In this tutorial, you'll learn how to use the Python time module to represent dates and times in your application, manage code execution, and measure performance.

intermediate

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 24, 2025