Learning center

A profiler names a hot function: real cost or the profiler's overhead?

Time the change without the profiler first: cProfile adds cost to every Python call, so a function called many times looks heavier than it is. Optimize what an unprofiled timing or a sampling profiler also ranks high.

Why a deterministic profiler inflates small calls#

cProfile records an event at every function call and return. Python's documentation is direct about the side effect: "the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one." It also names who pays most: "functions that are called many times, or call many functions, will typically accumulate this error." And it sets the tool's purpose: "The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes". profile and cProfile, Python 3.11.18

A function called 300,000 times collects that overhead 300,000 times. Its line in the profile then overstates what removing or inlining it would save. The same documentation suggests high call counts as "possible inline-expansion points", which is the change people reach for, so the overstated number usually becomes the target.

A profile that ranks a cheap helper high#

The module below is a constructed example: it parses 300,000 order lines and computes a score over them. The run used CPython 3.11.18 on a shared four-vCPU Linux VM. This is orders.py:

import random

random.seed(7)
LINES = [f"SKU{random.randrange(10**6)},{random.randrange(1, 9)},{random.random() * 100:.2f}"
         for _ in range(300_000)]


def is_valid(code):
    return code.startswith("SKU")


def parse(lines):
    rows = []
    for line in lines:
        code, qty, price = line.split(",")
        if is_valid(code):
            rows.append((code, int(qty), float(price)))
    return rows


def risk_score(rows):
    score = 0.0
    for code, qty, price in rows:
        x = qty * price
        for _ in range(8):
            x = (x * 1.0001 + 3.0) % 977.0
        score += x
    return score


def run():
    return risk_score(parse(LINES))

Profiled with cProfile.run("orders.run()", "out.prof") and printed by internal time (paths shortened):

         1200006 function calls in 0.744 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.283    0.283    0.512    0.512 orders.py:12(parse)
        1    0.223    0.223    0.223    0.223 orders.py:21(risk_score)
   300000    0.096    0.000    0.137    0.000 orders.py:8(is_valid)
   300000    0.067    0.000    0.067    0.000 {method 'split' of 'str' objects}
   300000    0.041    0.000    0.041    0.000 {method 'startswith' of 'str' objects}
   300000    0.025    0.000    0.025    0.000 {method 'append' of 'list' objects}

Read literally, parse is 69% of the run (0.512 of 0.744 s), is_valid alone is 18% (0.137 s), and risk_score is 30%. Three more runs gave totals of 0.705 to 0.837 s, with is_valid at 0.128 to 0.135 s each time. In the 0.837 s run risk_score moved above parse by internal time (0.314 s against 0.286 s), while parse stayed ahead by cumulative time. The charge to is_valid is repeatable; repeatability does not make it the program's cost.

Measure the change the profile suggests, without the profiler#

The obvious fix is to inline is_valid. parse_inline is parse with code.startswith("SKU") written in place of the call, and the script asserts it returns the same rows. The timing uses timeit, interleaves the three functions so a burst of load hits all of them, and keeps the minimum of 15 runs each. The timeit documentation explains the minimum: "the lowest value gives a lower bound for how fast your machine can run the given code snippet". timeit, Python 3.11.18

for _ in range(15):  # interleave the three so load changes hit all of them
    best["parse"] += timeit.repeat(lambda: orders.parse(orders.LINES), number=1, repeat=1)
    best["parse_inline"] += timeit.repeat(lambda: parse_inline(orders.LINES), number=1, repeat=1)
    best["risk_score"] += timeit.repeat(lambda: orders.risk_score(rows), number=1, repeat=1)
$ python3 wall.py
parse         min 0.131 s
parse_inline  min 0.122 s
risk_score    min 0.127 s
inlining is_valid saves 0.009 s
$ python3 wall.py
parse         min 0.124 s
parse_inline  min 0.114 s
risk_score    min 0.123 s
inlining is_valid saves 0.011 s

Unprofiled, the whole run takes about 0.25 s, a third of what cProfile reported. Inlining is_valid saves 0.009 to 0.011 s, about 4% of the run, where the profile implied 0.137 s and 18%. The four-percent saving, not the profile's 18%, is the number to weigh against the readability of a named check.

Cross-check with a sampling profiler#

A sampling profiler reads the stack at intervals instead of hooking every call, so the call count does not change what it charges. py-spy "doesn't run in the same process as the profiled Python program". py-spy 0.4.4 README Its README notes that "py-spy needs SYS_PTRACE to be able to read process memory", which some containers withhold; it worked in this one. Recording 20 iterations of run() at 250 samples per second:

$ py-spy record --rate 250 --format raw -o spy.txt -- python3 runloop.py
py-spy> Wrote raw flamegraph data to 'spy.txt'. Samples: 1863 Errors: 0
$ python3 spysum.py spy.txt
samples inside run(): 1756
risk_score    818  46.6%
parse         883  50.3%
is_valid       76   4.3%

spysum.py counts, for each function, the samples whose stack includes it, keeping only stacks under run(). The sampling view agrees with the timings: parse and risk_score split the run about evenly, and is_valid, including its startswith call, is about 4%, roughly 0.01 s of a 0.25 s run. Most of the 0.137 s on its cProfile line was the profiler's own per-call cost, charged 300,000 times. When the deterministic profile and the sampling profile disagree about a function with a high call count, the sampling profile and the timing are the better guide to what a change will save.

The disconfirmation: a hotspot that is real#

risk_score makes no Python calls inside its loop, so cProfile's per-call overhead cannot inflate it the same way. Its cost is real by every measure: timed alone it takes 0.123 to 0.127 s, half of the unprofiled run, and py-spy puts 46.6% of samples inside it. Any change that shortens its inner loop saves time in proportion to that half.

The profile still misled here, in the other direction. In the run shown, cProfile ranked risk_score at 30% of the run, behind parse's cumulative 69%, because the overhead it added to the 1.2 million calls under parse shifted the shares. Its absolute numbers for risk_score (0.214 to 0.314 s across runs) were also higher than the unprofiled 0.125 s, so seconds read from a cProfile run are not the program's seconds. A function the profile ranks second can be the better target, and only an unprofiled measurement shows it.

Decide from the unprofiled number#

What the finding saysEvidence to collectDecision
Small function with a very high call count near the top of cProfileUnprofiled timing of the code with and without the proposed changeMake the change only if the measured saving matters; record the measured number, not the profile's
Function with few calls and high internal timeIts unprofiled time, or its share in a sampling profileTreat it as real; optimize it first
cProfile ranks Python code above C calls it makesA sampling profile or timing of the C-heavy pathExpect C calls to be understated; rank by the sampling view
Profile shares differ from a sampling profileWhich functions have high call countsTrust the sampling shares for call-heavy functions
A profile from a single run on a busy machineThe profile repeated, and timings interleavedRepeat before acting; compare minimums, not single runs

When the evidence is a benchmark comparison rather than a profile, the guide to benchmark regressions and noise covers how many runs a decision needs. When a reviewer proposes the optimization, the guide to performance suggestions covers when it is worth taking.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading