Complexity and efficiency · 2 / 15 Theory

Measuring the running time

Theory says what should happen; measuring confirms what really happens. Python includes simple tools to time code, although they should be used carefully.

time.perf_counter

time.perf_counter() returns a high-precision clock. You take it before and after, and subtract.

import time

t0 = time.perf_counter()
total = sum(range(1_000_000))
t1 = time.perf_counter()

print(total)                    # 499999500000
print(f"{t1 - t0:.4f} seconds")   # a small value, different on every run

timeit: repeat to get a reliable value

A single measurement is affected by whatever the computer is doing at that moment. timeit runs the code many times and returns the total time. It takes the code as a function (callable) or as text.

import timeit

t = timeit.timeit(lambda: sum(range(1000)), number=1000)
print(f"{t:.4f} s for 1000 repetitions")   # the value changes depending on the computer

To compare two options, measure both in the same way and keep the ratio between them, not the exact value.

import timeit

list_data = list(range(10_000))
set_data = set(list_data)

in_list = timeit.timeit(lambda: 9_999 in list_data, number=1000)
in_set = timeit.timeit(lambda: 9_999 in set_data, number=1000)

print(in_list > in_set)   # True: searching in a list is much slower

The line print(in_list > in_set) does not depend on your machine's speed: looking for the last element in a list of 10 000 is hundreds of times slower than in a set.

Good practices when measuring

  • Repeat the measurement and keep the minimum (min(timeit.repeat(...))): it is the one with the least noise.
  • Measure with several input sizes (100, 1 000, 10 000). If multiplying *n* by 10 multiplies the time by 100, you have an O(n²).
  • Do not mix different tasks in the measurement (for example, creating the data and processing it): prepare the data outside.
  • Do not print inside what you measure: print is very slow.
  • Do not obsess over optimising before measuring: first make it work, then measure, and optimise only what is really slow.

Time versus counted steps

Measuring in seconds is useful in your real code, but it is not repeatable: each run gives a different value. That is why the exercises in this lesson count steps (comparisons, calls) instead of timing: the result is always the same and reflects the complexity of the algorithm.