typestar

Measuring code in Python

timeit runs it enough times to mean something, in an isolated namespace.

import timeit

setup = "values = list(range(1000))"

loop = timeit.timeit("total = 0\nfor v in values: total += v",
                     setup=setup, number=2000)
builtin = timeit.timeit("sum(values)", setup=setup, number=2000)

print(f"loop    {loop / 2000 * 1e6:.1f} us per call")
print(f"builtin {builtin / 2000 * 1e6:.1f} us per call")
print(f"{loop / builtin:.1f}x")
print(min(timeit.repeat("sum(values)", setup=setup, number=500, repeat=3)))

How it works

  1. number is how many repetitions to time.
  2. setup runs once and is not counted.
  3. Compare per-call cost, not the totals.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
426
Tokens
119
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 1 of 4 in Measuring & introspecting, step 35 of 41 in Domain tools.

← Previous Next →