← Writing

Profiling Below the Bytecode

15 min readSystemsPythonCpythonCProfilingPerf
Contents

A Python 3.8 program that splits strings, adds up their lengths and writes JSON takes 4.5 seconds. cProfile says 3.1 of them are in str.split. py-spy says two thirds of the samples are in the list comprehension that calls it. perf, the Linux profiler, says a third of the time is in a C function called collect, and another quarter in functions it calls, and it doesn’t name a single Python function. All three are right about what they measure, and only one of them found the real problem: the cycle collector from Part 4, walking three million lists that will never be garbage. With the collector turned off, the same program runs in 1.9 seconds.

This post profiles that one program with every kind of tool available for CPython: a deterministic profiler inside the interpreter, a sampling profiler outside it, a native profiler that sees only C, a debugger that sees both, and the static tracing probes compiled into the interpreter itself. Each shows a different layer of the same execution, and each one’s blind spot is a fact about CPython.

This is Part 13 of a series on the CPython runtime. Part 2 measured the cost of trace hooks, and Part 4 introduced the cycle collector that this post catches at work. It is written for Python programmers who have written a little C. Everything here ran on CPython 3.8.1 (December 2019), built from its tag with Ubuntu 18.04’s gcc 7.3.0 and with --with-dtrace, in a virtual machine booting 18.04’s release kernel, with py-spy 0.3.2 and the release archive’s perf and BCC. The note at the end says exactly where and how.

The program

import json, sys

def parse(lines):
    return [line.split(",") for line in lines]

def score(rows):
    total = 0
    for row in rows:
        for field in row:
            total += len(field) * 31 % 7
    return total

def report(rows):
    return json.dumps(rows)

def main(rounds):
    lines = ["alpha,beta,gamma,%d" % i for i in range(300000)]
    for _ in range(rounds):
        rows = parse(lines)
        s = score(rows)
        out = report(rows)
    print("done", s, len(out))

main(int(sys.argv[1]) if len(sys.argv) > 1 else 10)

Three functions, ten rounds: parse turns 300,000 lines into 300,000 four-element lists, score loops over every field, and report encodes them all as JSON. A small helper times commands, best of three runs:

# wall.py: run each command three times and report the best wall time
import subprocess, sys, time
for cmd in sys.argv[1:]:
    best = min(_t for _t in (lambda: [(lambda t: (subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), time.perf_counter() - t)[1])(time.perf_counter()) for _ in range(3)])())
    print("%6.2f s  %s" % (best, cmd))

cProfile: every call, from inside

cProfile is a C module that installs a profile function with PyEval_SetProfile. The eval loop calls it on every Python function call and return, and on every call into and return from a C function. It records exact call counts and times, which makes it deterministic: nothing is sampled.

$ python3 -m cProfile -s tottime slow.py | head -16
done 3037370 11288890
         15003139 function calls (15003029 primitive calls) in 5.141 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  3000000    3.088    0.000    3.088    0.000 {method 'split' of 'str' objects}
       10    0.751    0.075    1.065    0.106 slow.py:6(score)
       10    0.584    0.058    0.584    0.058 encoder.py:204(iterencode)
12000319/12000291    0.314    0.000    0.314    0.000 {built-in method builtins.len}
        1    0.171    0.171    5.098    5.098 slow.py:16(main)
       10    0.145    0.014    3.233    0.323 slow.py:4(<listcomp>)
        1    0.024    0.024    5.141    5.141 slow.py:1(<module>)
       69    0.023    0.000    0.023    0.000 {method 'join' of 'str' objects}
        1    0.021    0.021    0.021    0.021 slow.py:17(<listcomp>)
       24    0.006    0.000    0.006    0.000 {built-in method posix.stat}

Its verdict: str.split took 3.09 of 5.14 seconds of own time (tottime), called three million times; score 0.75; the JSON encoder 0.58. The program is mostly splitting strings, it says, and a reader would start optimising there. len was called twelve million times, which is accurate and beside the point.

It also cost something. The profile function runs twice per call, for 15 million calls, and the run took 5.14 seconds where the program alone takes about 4.5. And it can only see calls: anything the interpreter does that isn’t a function call is billed to whichever call was active when it happened. Keep that in mind for later.

py-spy: samples, from outside

py-spy (by Ben Frederickson, first released in 2018) is a sampling profiler written in Rust that runs as a separate process. A hundred times a second it reads the target’s memory with Linux’s process_vm_readv system call, finds the interpreter’s state through the _PyRuntime symbol, and walks the chain of PyFrameObjects from Part 2, reading each frame’s code object for a function name and its f_lasti for a line. The target isn’t modified, doesn’t run any extra code, and doesn’t know it’s being watched.

$ py-spy record --format raw -o pyspy.txt -- python3 slow.py
Sampling process 100 times a second. Press Control-C to exit.

Stopped sampling because process exitted
Wrote raw flamegraph data to 'pyspy.txt'. Samples: 421 Errors: 0
You can use the flamegraph.pl script from https://github.com/brendangregg/flamegraph to generate a SVG

The raw format is one line per distinct stack with its sample count. A few lines of Python reduce it to the innermost frame of each sample, which is where the time was going:

# topself.py: from py-spy's raw (collapsed) output, count samples by the innermost frame
import collections, sys
counts, total = collections.Counter(), 0
for line in open(sys.argv[1]):
    stack, n = line.rsplit(" ", 1)
    n = int(n); total += n
    counts[stack.split(";")[-1]] += n
print(total, "samples")
for frame, n in counts.most_common(6):
    print("%5.1f%%  %s" % (100.0 * n / total, frame))
$ python3 topself.py pyspy.txt
403 samples
 67.5%  <listcomp> (slow.py:4)
 11.7%  iterencode (json/encoder.py:257)
 11.2%  score (slow.py:10)
  4.2%  main (slow.py:19)
  1.7%  score (slow.py:9)
  1.0%  encode (json/encoder.py:202)

Its verdict: 67.5% of the samples were on line 4, inside the list comprehension of parse. That’s the same answer as cProfile’s in a different unit: py-spy 0.3 reports only Python frames by default, and str.split is a C function, so its time shows up on the Python line that called it. The score loop and the JSON encoder share most of the rest.

py-spy can also look at a process that’s already running, which no in-process profiler can do:

$ python3 slow.py 40 > /dev/null &
$ py-spy dump --pid $!
Process 320: python3 slow.py 40
Python v3.8.1 (/opt/py/3.8.1/bin/python3.8)

Thread 320 (active+gil)
    <listcomp> (slow.py:4)
    parse (slow.py:4)
    main (slow.py:19)
    <module> (slow.py:24)

perf: the C that’s actually running

perf is the Linux kernel’s own profiler. It samples the CPU’s instruction pointer and call stack through the kernel, and it knows nothing about Python, only native code and its symbols:

$ perf record -q -F 999 -g -o /dev/shm/perf.data python3 slow.py > /dev/null
$ perf report -i /dev/shm/perf.data --stdio --no-children -g none --percent-limit 1.5 --sort symbol | grep -v "^#" | grep "%"
    33.64%  [.] collect.constprop.34
    11.38%  [.] visit_reachable
    10.84%  [.] visit_decref
     4.08%  [.] list_traverse
     3.82%  [.] _PyEval_EvalFrameDefault
     2.72%  [k] __do_page_fault
     2.66%  [.] _PyObject_Malloc
     2.61%  [k] _raw_spin_lock
     2.35%  [.] list_dealloc
     2.07%  [.] PyUnicode_Join
     2.05%  [.] py_encode_basestring_ascii
     1.71%  [.] _PyObject_Free

This is a different program. The top four symbols, collect, visit_reachable, visit_decref and list_traverse, are all in Modules/gcmodule.c, the cycle collector, and together they take 60% of the samples. visit_decref and visit_reachable are the subtract_refs and move_unreachable passes from Part 4’s box, and list_traverse is how they reach into lists. The eval loop, _PyEval_EvalFrameDefault, is 3.8%. str.split’s own C code isn’t even in the list.

And not one Python function appears. To perf, every Python function is _PyEval_EvalFrameDefault, the same C function interpreting a different code object, so a native profiler of a Python program profiles the interpreter, never the program. It can tell you that the collector is busy, but not which Python code made it busy.

gdb: both stacks at once

A debugger stops the process and shows everything. With CPython’s own gdb extension, Tools/gdb/libpython.py from the source tree, which teaches gdb to read PyFrameObjects, py-bt prints the Python stack of a stopped process:

$ python3 slow.py 40 > /dev/null &
$ gdb -q -p $! -batch -ex "source libpython.py" -ex "py-bt"
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
gc_list_size (list=0x55bc005d1f00 <_PyRuntime+416>) at /opt/src/cpython-v3.8.1/Modules/gcmodule.c:296
296	        n++;
Traceback (most recent call first):
  Garbage-collecting
  File "slow.py", line 4, in <listcomp>
    return [line.split(",") for line in lines]
  File "slow.py", line 4, in parse
    return [line.split(",") for line in lines]
  File "slow.py", line 19, in main
    rows = parse(lines)
  File "slow.py", line 24, in <module>
    main(int(sys.argv[1]) if len(sys.argv) > 1 else 10)

One random stop, and it landed in gc_list_size, in gcmodule.c, with py-bt reporting Garbage-collecting above the Python frames: the collector, running inside the list comprehension of parse, at line 4. That’s the whole story in one picture, the C at the top and the Python underneath. It’s also a single sample, and the odds of catching it there were the 60% that perf measured.

The same 4.5-second program, three profilers, three culprits

CPython 3.8.1 running slow.py. Each tool's top entries, in its own unit.

cProfile · own time, s

"It's str.split."

{method 'split' of 'str' objects}
3.088 s
slow.py:6(score)
0.751 s
encoder.py:204(iterencode)
0.584 s
slow.py:16(main)
0.171 s

py-spy · samples, innermost frame

"It's line 4."

<listcomp> (slow.py:4)
67.5%
iterencode (json/encoder.py:257)
11.7%
score (slow.py:10)
11.2%
main (slow.py:19)
4.2%

perf · samples, C symbol

"It's the cycle collector."

collect.constprop.34 cycle collector
33.64%
visit_reachable cycle collector
11.38%
visit_decref cycle collector
10.84%
list_traverse cycle collector
4.08%
_PyEval_EvalFrameDefault
3.82%
__do_page_fault
2.72%

Hover or focus a bar for details.

All three are accurate about what they measure. Turning the collector off took the program from 4.62 to 1.94 seconds: perf's answer was the one that pointed at the cause.

What was really happening

parse builds 300,000 new lists per round, and every list is a container that the collector tracks. Part 4 showed what that triggers: a generation-0 collection every 700 net container allocations, a generation-1 every 10 of those, and full collections of everything whenever the survivors grow by a quarter. The lists survive, because rows holds them, so every collection walks them and frees nothing, and the full ones walk all of them. That work happens inside whatever allocation crossed the threshold, which here is the list allocated by str.split. So cProfile, which bills by call, charged it to split, py-spy, which bills by Python line, charged it to the comprehension, and perf, which bills by C function, charged it to collect. The cure isn’t faster splitting:

import gc, runpy
gc.disable()                            # the experiment: no cycle collection at all
runpy.run_path("slow.py", run_name="__main__")
$ python3 wall.py "python3 slow.py" "python3 nogc.py"
  4.62 s  python3 slow.py
  1.94 s  python3 nogc.py

Without the collector the program takes 1.94 seconds instead of 4.62, 58% less, which is what perf said. (Disabling it is only safe here because this program makes no reference cycles. gc.freeze() after building the data, or raising the thresholds with gc.set_threshold, are the gentler versions.) The collector is part of the interpreter, not of any function, so a profiler that can only see functions can’t show it as itself.

What watching costs

$ python3 wall.py "python3 slow.py" "python3 -m cProfile -o /dev/null slow.py" "py-spy record --format raw -o /dev/null -- python3 slow.py"
  4.51 s  python3 slow.py
  5.36 s  python3 -m cProfile -o /dev/null slow.py
  4.56 s  py-spy record --format raw -o /dev/null -- python3 slow.py
$ python3 wall.py "python3 slow.py" "perf record -q -F 999 -g -o /dev/shm/p.data python3 slow.py"
  4.49 s  python3 slow.py
  7.92 s  perf record -q -F 999 -g -o /dev/shm/p.data python3 slow.py

What watching costs, and what the collector cost

Wall time of slow.py, best of three, CPython 3.8.1 on Linux 4.15 in a VM.

no tool (baseline)
4.51 s · 1.00×
cProfile
5.36 s · 1.19×
py-spy record
4.56 s · 1.01×
perf record -g
7.92 s · 1.76×
gc.disable(), no tool
1.94 s · 0.42× of its own baseline (4.62 s)

py-spy reads the process from outside and costs almost nothing; cProfile runs code on every call; perf's cost here is mostly the virtual machine's handling of its sampling, and I didn't establish its cause. The last bar is the fix the profilers were pointing at, or failing to.

py-spy cost 1%: it runs in another process, and the target only pays for the moments its memory is read. cProfile cost 19% on this program, little because most of the time was in C calls that are profiled once each. On code made of many small Python calls the same tracing costs several times more, as Part 2 found for trace functions. perf with call graphs cost 76% in this virtual machine. That’s unusually high, and I didn’t establish why, but most of perf’s cost is in the kernel and the virtual machine’s handling of its sampling interrupts, not in the program.

Probes compiled into the interpreter

CPython can be built with static tracing markers, USDT probes: ./configure --with-dtrace, available since 3.6. They compile into the binary as notes that say “at this instruction, a probe called function__entry with these arguments”. Until a tracer enables one, each costs a test of a variable, the probe’s semaphore. The eval loop, for example, runs if (PyDTrace_FUNCTION_ENTRY_ENABLED()) dtrace_function_entry(f); on every frame. The list, from the binary itself:

$ tplist-bpfcc -l /opt/py/3.8.1/bin/python3.8
/opt/py/3.8.1/bin/python3.8 python:line
/opt/py/3.8.1/bin/python3.8 python:function__entry
/opt/py/3.8.1/bin/python3.8 python:function__return
/opt/py/3.8.1/bin/python3.8 python:import__find__load__start
/opt/py/3.8.1/bin/python3.8 python:import__find__load__done
/opt/py/3.8.1/bin/python3.8 python:audit
/opt/py/3.8.1/bin/python3.8 python:gc__start
/opt/py/3.8.1/bin/python3.8 python:gc__done

Linux’s perf can see them too:

$ perf buildid-cache --add /opt/py/3.8.1/bin/python3.8
$ perf list sdt | grep python
  sdt_python:audit                                   [SDT event]
  sdt_python:function__entry                         [SDT event]
  sdt_python:function__return                        [SDT event]
  sdt_python:gc__done                                [SDT event]
  sdt_python:gc__start                               [SDT event]
  sdt_python:import__find__load__done                [SDT event]
  sdt_python:import__find__load__start               [SDT event]
  sdt_python:line                                    [SDT event]
$ perf probe -q sdt_python:function__entry
$ perf stat -e sdt_python:function__entry python3 slow.py 1
done 3037370 11288890

 Performance counter stats for 'python3 slow.py 1':

                 0      sdt_python:function__entry                                   

       0.558663852 seconds time elapsed

Zero function entries, from a one-round run that made about a million and a half calls. CPython’s probes are guarded by semaphores, and the probe only fires if a tracer increments the semaphore in the target’s memory first. The perf in 18.04 (4.15) finds the probe and attaches to its address, but this version doesn’t set semaphores, so the guarded code never runs and the probe is never reached. BCC, the BPF Compiler Collection, whose tools are in 18.04 as bpfcc-tools, does set them:

$ python3 slow.py 40 > /dev/null &
$ python2 /usr/sbin/lib/ucalls -l python $! 3
Tracing calls in process 268 (language: python)... Ctrl-C to quit.

METHOD                                              # CALLS
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.encode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
/opt/py/3.8.1/lib/python3.8/json/encoder.py.iterencode        1
slow.py.score                                             7
slow.py.report                                            7
slow.py.<listcomp>                                        7
slow.py.parse                                             7
/opt/py/3.8.1/lib/python3.8/json/__init__.py.dumps        7
^C

ucalls attached to the running process, switched the function__entry probe on, and counted Python calls by function, from outside, with no change to the program: seven rounds of parse, score, the comprehension and report in its first three-second interval. (I stopped it with Ctrl-C after the first interval. The repeated encode and iterencode lines, each counted 1, are a quirk of this BCC release’s key handling, which seems to keep stale bytes in the fixed-size name buffer. Their sum is 7 each.) The probes cost almost nothing when off, and give a trace of every call when on. Ubuntu’s own Python 3.6 package isn’t built with them (its sysconfig.get_config_var("CONFIG_ARGS") has no --with-dtrace). A Python built with --with-dtrace is the only kind where this works.

What we covered

  • cProfile traces every call from inside, deterministically, at 19% overhead on this program, and bills everything that happens during a call to that call.
  • py-spy samples from outside by reading the interpreter’s frames with process_vm_readv, at 1% overhead. It reports Python lines, so a C function’s time appears on the line that called it.
  • perf sees only C. Here that showed 60% of the time in the cycle collector, and no Python functions at all, because every one of them is _PyEval_EvalFrameDefault.
  • gdb with CPython’s libpython.py shows both stacks, and one stop caught the collector inside the comprehension.
  • The real cost was Part 4’s cycle collector, repeatedly walking three million long-lived lists. Disabling it cut 4.62 s to 1.94 s. No function-level profiler could name it.
  • --with-dtrace builds carry eight USDT probes. perf 4.15 lists them but counts nothing, because the probes are guarded by semaphores it doesn’t set. BCC’s ucalls sets them and counts calls by function.

The next post looks at the other engines that run Python, PyPy above all, and at why the C API, the thing that made every tool in this post possible, is also what makes replacing CPython so hard.

A note on the evidence

What I ran, and where. Everything ran in a KVM virtual machine (4 virtual CPUs, 4 GiB) booting Ubuntu 18.04’s release kernel 4.15.0-20-generic, on a minimal 18.04 userland from the release archive, with CPython 3.8.1 built from the v3.8.1 tag with gcc 7.3.0 and --with-dtrace, py-spy 0.3.2 from PyPI (the newest on the date), and perf (linux-tools-4.15.0-20-generic), BCC (bpfcc-tools 0.5.0-5ubuntu1) and the matching kernel headers from the release archive. libpython.py is the file from the v3.8.1 tag’s Tools/gdb. Each script was extracted from this page and run as shown, with outputs captured to files and pasted from them.

The numbers. Wall times are the best of three runs, from two invocations of wall.py in the same VM session. The slow.py baseline measured 4.51, 4.49 and 4.62 s across them, so differences of a few percent are noise. Profiler percentages are from one run each. py-spy’s 421 samples are few enough that its percentages could move by a few points between runs. The gdb stop is one sample. A complete rerun of every command on this page gave the collector 59.8% in perf (60.0% here), 72% of py-spy’s samples on line 4, 4.55 against 1.89 seconds without the collector, and the same overheads within 5%, and gdb’s one stop landed in the collector again, in a different function of gcmodule.c.

What I worked out rather than read. That the collections were triggered inside str.split’s allocations, and so billed to it, follows from cProfile’s design and Part 4’s thresholds; I didn’t trace which allocation triggered each collection. The cause of perf’s 76% overhead is unexplained. The BCC duplicate-key explanation is a guess from the output.

What I cited rather than ran. The probe guard is from Python/ceval.c and Include/pydtrace.h at v3.8.1, and --with-dtrace from the 3.6 “What’s New”. How py-spy reads memory is from its README and source. That this perf doesn’t set the semaphores is inferred from the zero count, against BCC’s nonzero one on the same binary. I didn’t test a newer perf.

What I’d still change. py-spy 0.3 can also sample native frames (--native), which would have shown the collector inside the Python stack, and I didn’t try it. And a flame graph of the perf data, with Python frames merged in from the probes, would show all the layers at once.

More