ZetCode

Python timeit

last modified November 29, 2026 Python 3.15

In this article we show how to measure the execution time of small pieces of code with the timeit module.

Timing a single run of a fast statement is unreliable: the result is dominated by the resolution of the clock and by noise from the operating system. The timeit module runs the code many times in a loop and reports the total time. It uses the high-resolution time.perf_counter clock and turns off the garbage collector during the measurement, so that collections do not distort the results. The module is part of the standard library.

The timings in this article come from one run on one machine. They vary between runs, machines, and Python versions; what matters is the ratio between alternatives measured on the same machine.

The first measurement

The timeit.timeit function takes a statement as a string, runs it number times, and returns the total time in seconds.

first_timing.py
import timeit

number = 1_000_000
total = timeit.timeit('"-".join(["a", "b", "c"])', number=number)

print(f'total: {total:.3f} s')
print(f'per loop: {total / number * 1e9:.1f} ns')

The statement joins three strings a million times. The default number is one million as well, which is too much for slower statements. Dividing the total by the number of loops gives the time of one execution, here in nanoseconds.

$ python first_timing.py
total: 0.075 s
per loop: 74.5 ns

Setup code

The setup argument is code that runs before the measurement and is not timed. It prepares imports and data for the statement.

setup_code.py
import timeit

setup = '''
import random
random.seed(1)
data = [random.randint(0, 1000) for _ in range(1000)]
'''

t1 = timeit.timeit('sorted(data)', setup=setup, number=10_000)
t2 = timeit.timeit('data.sort()', setup=setup, number=10_000)
t3 = timeit.timeit('data.copy().sort()', setup=setup, number=10_000)

print(f'sorted(data):       {t1:.3f} s')
print(f'data.sort():        {t2:.3f} s')
print(f'data.copy().sort(): {t3:.3f} s')

The setup creates a list of a thousand random numbers. It runs once per measurement, not once per loop, and this matters for statements that change the data. The data.sort() call sorts the list in place, so all runs after the first one sort an already sorted list, which Python's sort handles in linear time. The result looks much faster than sorted, but it measures something else. Sorting a fresh copy gives an honest comparison: in-place sorting of a copy costs about the same as sorted, which also copies the list.

$ python setup_code.py
sorted(data):       0.507 s
data.sort():        0.032 s
data.copy().sort(): 0.504 s

Timing functions

The statement may also be a callable without arguments. Alternatively, the globals argument lets a string statement use names from our module.

callables.py
import timeit


def squares_loop(n):
    result = []
    for i in range(n):
        result.append(i * i)
    return result


def squares_comprehension(n):
    return [i * i for i in range(n)]


n = 1000

t1 = timeit.timeit(lambda: squares_loop(n), number=10_000)
t2 = timeit.timeit('squares_comprehension(n)', globals=globals(), number=10_000)

print(f'loop:          {t1:.3f} s')
print(f'comprehension: {t2:.3f} s')

The lambda calls the function with an argument; it adds the small cost of one extra function call to each loop. Passing globals() runs the statement in the namespace of the module, so it can see squares_comprehension and n. Without it, the statement would run in an empty namespace and fail with a NameError. The comprehension is faster than the loop with append.

$ python callables.py
loop:          0.236 s
comprehension: 0.203 s

Repeating the measurement

The repeat function makes several measurements and returns a list of the totals. The default is five repetitions.

repeat_runs.py
import timeit

times = timeit.repeat('sum(range(10_000))', repeat=5, number=1000)

for t in times:
    print(f'{t * 1000:.2f} ms')

best = min(times)
print(f'best: {best / 1000 * 1e6:.1f} us per loop')

The measurements differ because other processes and the system compete for the CPU. Such interference only makes the code slower, never faster, so the minimum is the best estimate of how fast the code can run. The mean and the standard deviation of the list are usually not meaningful.

$ python repeat_runs.py
73.84 ms
74.44 ms
74.17 ms
73.18 ms
75.46 ms
best: 73.2 us per loop

The Timer class

The functions of the module are shortcuts for the Timer class. Its autorange method finds a suitable number of loops automatically.

timer_class.py
import timeit

timer = timeit.Timer('text.upper()', setup='text = "an old falcon " * 100')

loops, total = timer.autorange()
print(f'{loops} loops in {total:.3f} s')

loops, total = timer.autorange(target_time=1.0)
print(f'{loops} loops in {total:.3f} s')

best = min(timer.repeat(repeat=5, number=loops)) / loops
print(f'best: {best * 1e6:.2f} us per loop')

The autorange method tries 1, 2, 5, 10, 20, 50, and more loops until the total time reaches the target and returns the number of loops and the time they took. The target is 0.2 seconds by default; the target_time parameter, new in Python 3.15, changes it. The number of loops is then used for repeat, which is how the command line interface works.

$ python timer_class.py
500000 loops in 0.260 s
2000000 loops in 1.041 s
best: 0.52 us per loop

The command line

The module can be run with python -m timeit. It picks the number of loops automatically, repeats the measurement five times, and prints the best time per loop.

The -s option gives the setup code, -n the number of loops, -r the number of repetitions, and -u the unit of the result. The -t option, added in Python 3.15, sets the target time for choosing the number of loops; with a longer target, the measurement takes longer but is more stable. A multi-line statement is given as several arguments, one per line.

$ python -m timeit 'sum(range(1000))'
100000 loops, best of 5: 3.42 usec per loop
$ python -m timeit -s 'data = list(range(1000))' 'sum(data)'
100000 loops, best of 5: 3.16 usec per loop
$ python -m timeit -n 1000 -r 3 -u usec 'sum(range(1000))'
1000 loops, best of 3: 3.25 usec per loop
$ python -m timeit -t 1 'sum(range(1000))'
500000 loops, best of 5: 3.38 usec per loop

Comparing alternatives

A typical use of timeit is to compare several ways of doing the same thing. Here we compare three ways of building a string from a list of words.

compare.py
import io
import timeit

words = ['falcon', 'sky', 'cloud', 'water', 'rock'] * 200

candidates = {
    'plus': '''
s = ''
for w in words:
    s += w
''',
    'join': "''.join(words)",
    'stringio': '''
buf = io.StringIO()
for w in words:
    buf.write(w)
s = buf.getvalue()
''',
}

results = {}

for name, stmt in candidates.items():
    timer = timeit.Timer(stmt, globals={'words': words, 'io': io})
    loops, _ = timer.autorange()
    results[name] = min(timer.repeat(repeat=5, number=loops)) / loops

fastest = min(results.values())

for name, best in sorted(results.items(), key=lambda item: item[1]):
    print(f'{name:<9} {best * 1e6:8.2f} us  {best / fastest:5.1f}x')

Each candidate is a statement; multi-line statements are written as triple-quoted strings. For each of them, autorange picks the number of loops and the best of five repetitions is taken. The results are sorted from the fastest and shown relative to it. The join method is the clear winner: it computes the final size once and copies each word once.

$ python compare.py
join          4.04 us    1.0x
stringio     27.37 us    6.8x
plus         35.02 us    8.7x

Scaling with the input size

A single measurement says little about how the time grows with the size of the data. In the last example we measure a membership test in a list and in a set for several sizes.

membership.py
import timeit

print(f'{"size":>8} {"list":>12} {"set":>12}')

for size in [10, 100, 1000, 10_000]:
    values = list(range(size))
    lookup = set(values)
    target = size - 1

    t_list = min(timeit.repeat(lambda: target in values, repeat=5, number=1000))
    t_set = min(timeit.repeat(lambda: target in lookup, repeat=5, number=1000))

    print(f'{size:>8} {t_list / 1000 * 1e9:>9.0f} ns {t_set / 1000 * 1e9:>9.0f} ns')

The target is the last element, the worst case for a list. A list is searched element by element, so the time grows linearly with its size. A set is a hash table and finds the element in roughly constant time. Each lambda is timed right after it is created, so it sees the current values and lookup.

$ python membership.py
    size         list          set
      10        85 ns        29 ns
     100       623 ns        29 ns
    1000      6069 ns        27 ns
   10000     62205 ns        34 ns

Source

Python timeit documentation

In this article we have measured the execution time of small code snippets with the timeit module: setup code, timing functions, repeated measurements, the Timer class with autorange, the command line interface, and comparisons of alternatives. See also Python time.perf_counter, Python memory_profiler, and Python time module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.