Reading history

Python timeit and cProfile: Measuring Speed

7 min read 1 views

Measure Python code speed with timeit, find slow functions with cProfile and pstats, and follow a simple method to make programs faster.

“This program is slow” is not enough to fix it. You need to know which part is slow, and whether your change really helped. Guessing is often wrong. Python has two built-in tools for measuring: timeit times small pieces of code, and cProfile shows where a whole program spends its time. This lesson shows how to use both, and how to act on what they tell you.

In this lesson you will learn

  • Timing small pieces of code with timeit
  • Why you should take the minimum of several runs
  • Finding slow functions with cProfile and pstats
  • A simple timer with time.perf_counter
  • A step-by-step way to speed up a program

You should know functions, context managers and functools.lru_cache.

Timing Small Code With timeit

import timeit

# timeit runs a small piece of code many times and returns the total seconds.
# repeat() does that several times; the minimum is the most reliable figure.
setup = "nums = list(range(10_000))"
loop = """
total = 0
for n in nums:
    total += n
"""
builtin = "total = sum(nums)"

t_loop = min(timeit.repeat(loop, setup, number=200, repeat=5))
t_sum = min(timeit.repeat(builtin, setup, number=200, repeat=5))
print("built-in sum() faster than a for loop?", t_sum < t_loop)

# Membership test: list vs set
setup2 = "items = list(range(50_000)); s = set(items)"
t_list = min(timeit.repeat("49_999 in items", setup2, number=2000, repeat=5))
t_set = min(timeit.repeat("49_999 in s", setup2, number=2000, repeat=5))
print("set lookup at least 50x faster than list?", t_list / t_set > 50)

# Timing a function directly: pass the function itself, no quotes
def join_words():
    return " ".join(str(i) for i in range(1000))

def plus_words():
    s = ""
    for i in range(1000):
        s += str(i) + " "
    return s

print("join result same as += result?", join_words() == plus_words().rstrip())
t_join = min(timeit.repeat(join_words, number=500, repeat=5))
print("join_words takes under 1 ms per call?", t_join / 500 < 0.001)

Output

built-in sum() faster than a for loop? True
set lookup at least 50x faster than list? True
join result same as += result? True
join_words takes under 1 ms per call? True
  • timeit.repeat(code, setup, number, repeat) runs setup once, then runs code number times and measures the total. It does this repeat times and returns a list of totals.
  • Take the minimum. Other programs on the computer can only slow a run down, never speed it up, so the fastest run is the fairest one.
  • Exact times change from computer to computer, so this example prints comparisons instead of seconds. On your machine, print the numbers too.
  • The built-in sum() runs in fast C code, so it beats a Python loop.
  • Checking x in a_list looks at items one by one. Checking x in a_set jumps straight to the answer. With 50,000 items the set is far faster.
  • You can pass a function instead of a string. Always check that the old and new versions give the same result before you compare their speed.

From the command line, python -m timeit "sum(range(1000))" times a one-line expression.

Finding the Slow Part With cProfile

import cProfile, pstats, time
from contextlib import contextmanager
from functools import lru_cache

# A tiny timer you can wrap around any block
@contextmanager
def timer(label, results):
    start = time.perf_counter()
    yield
    results[label] = time.perf_counter() - start

# A slow program: naive Fibonacci called many times
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

def report():
    return [fib(n) for n in range(20)]

# cProfile counts every function call and measures time
profiler = cProfile.Profile()
profiler.enable()
values = report()
profiler.disable()
print("last value:", values[-1])

stats = pstats.Stats(profiler)
for (file, line, func), (cc, ncalls, tt, ct, callers) in stats.stats.items():
    if func in ("fib", "report"):
        print(f"{func:7} called {ncalls:,} times")

# The profile shows fib is the problem. Fix it with a cache, then measure.
@lru_cache(maxsize=None)
def fast_fib(n):
    return n if n < 2 else fast_fib(n - 1) + fast_fib(n - 2)

times = {}
with timer("slow", times):
    report()
with timer("fast", times):
    [fast_fib(n) for n in range(20)]
print("same answers?", [fast_fib(n) for n in range(20)] == values)
print("cached version at least 10x faster?", times["slow"] / times["fast"] > 10)
print("fast_fib cache info:", fast_fib.cache_info())

Output

last value: 4181
fib     called 35,400 times
report  called 1 times
same answers? True
cached version at least 10x faster? True
fast_fib cache info: CacheInfo(hits=56, misses=20, maxsize=None, currsize=20)
  • cProfile records every function call while the program runs: how many times each function was called and how long it took.
  • Here the profile reveals the problem at once: report runs once, but fib is called 35,400 times, because it works out the same values again and again.
  • The fix is lru_cache, which remembers answers. The cached version makes only 20 real calculations (the “misses”). The answers stay the same, and it runs many times faster.
  • The cache info shows 20 misses and 56 hits: each new value reused two stored ones, and the final check asked for all 20 again.
  • The timer context manager uses time.perf_counter(), the most precise clock for measuring short times.

To profile a whole script without changing it, run python -m cProfile -s cumulative myscript.py. It prints a table of every function, sorted by total time.

How to Speed Up a Program

  1. Make it correct first, with tests, so you can check that a faster version still gives the same answers.
  2. Measure with cProfile to find where the time goes. Usually one or two functions take most of it.
  3. Fix the biggest cost: a better algorithm, a set or dictionary instead of a list search, caching, or a built-in function.
  4. Measure again to prove the change helped. If it did not, undo it and keep the simpler code.
Slow patternFaster choice
if x in big_list inside a loopConvert to a set once, then test the set
Same calculation repeatedfunctools.lru_cache
s += piece in a long loopCollect pieces, then "".join(pieces)
Python loop for sums and countssum, max, collections.Counter

Common Mistakes

  1. Optimizing without measuring, which often makes code harder to read and no faster.
  2. Timing one single run, which mostly measures noise. Repeat and take the minimum.
  3. Putting setup inside the timed code, such as building the list each time, so you measure the wrong thing.
  4. Comparing versions that give different answers. A fast wrong answer is no use.

Practice Exercises

Exercise 1. Use timeit to compare "-".join(words) with a loop that adds each word to a string, for words = ["a"] * 1000.

Show answer
import timeit

setup = 'words = ["a"] * 1000'
loop = """
s = ""
for w in words:
    s += w + "-"
"""
t_join = min(timeit.repeat('"-".join(words)', setup, number=2000, repeat=5))
t_loop = min(timeit.repeat(loop, setup, number=2000, repeat=5))
print("join faster?", t_join < t_loop)

Note that the loop leaves an extra dash at the end; check results match before trusting a comparison.

Exercise 2. A profile shows that find_user is called 10,000 times and searches a list of 50,000 users by ID each time. Suggest a fix.

Show answer

Build a dictionary once, users_by_id = {u.id: u for u in users}, and look up users_by_id[id]. Each lookup becomes almost instant instead of scanning the whole list.

Frequently Asked Questions

Why does profiling make my program slower?

The profiler does extra work on every function call, so programs run slower while profiled. The slowdown is spread fairly evenly, so the relative numbers still point to the slow parts.

Is there a profiler that shows time per line?

Yes. Third-party tools such as line_profiler show time for each line, and py-spy can watch a running program without changing it. Start with the built-in cProfile; it is enough for most problems.

Summary

  • timeit.repeat times small code many times; use the minimum.
  • cProfile counts calls and time per function, to find the slow part.
  • time.perf_counter is the precise clock for your own timers.
  • Measure, fix the biggest cost, then measure again.

Next: Python Project: Student Result System.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *