Your API endpoint takes 900 ms and every unit test still passes. You reach for the standard library profiler, rerun the request, and the numbers come back warped: because cProfile hooks every single call and return, its overhead reshapes the hot paths you are chasing, and in async code the event loop machinery drowns out your handlers entirely. Deterministic tracing answers “how many times was this function called,” but the act of measuring changes the thing you are measuring.
pyinstrument — Joe Rickerby’s call stack profiler, at version 5.1.4 in the tree we inspected — takes the opposite bet. Instead of instrumenting every call, it sets a timer, wakes up on an interval (one millisecond by default), and records whatever happens to be on the Python stack at that moment. The report reads like “your code spent 62% of this request inside template rendering,” which is usually the question you actually had. Statistical sampling has blind spots, but its cost is nearly flat regardless of call frequency, and its async story is far more honest than tracing.
The best reason to read this codebase, though, is that it is small and deliberately layered: a few hundred lines of C doing the timing-critical work, a strict Python core that owns the data model, and a renderer layer that keeps output format questions out of the capture path. This post walks the real tree of joerick/pyinstrument on the main branch. Every symbol and line number below was checked against the repository as it stands today.
pyinstrument architecture: three entry points funnel into one Profiler core; the core subscribes to a per-thread sampler that talks to the C extension; samples accumulate into a Session, get replayed into a Frame tree, pass through processors, and finally reach one of seven renderers.
Reading the overview from left to right:
- Profiler, L45 — the public class. Its constructor takes
interval=0.001seconds andasync_mode="enabled"(L56-59);start()andstop()bracket the target code, andstop()folds the accumulated samples intolast_session, merging with any previous session (L207-211). - StackSampler, L54 — a per-thread registry of subscribers stored in
thread_locals. When several profilers subscribe at once,_update()restarts sampling at the minimum requested interval (L134-148), so nested profilers share one hook. - setstatprofile, L749 — the C extension’s entire public surface: a target callback, an interval, a context var, a timer type and an optional timer function, installed via
PyEval_SetProfileat L832. - profile, L636 — the callback CPython invokes on every profiling event. It compares the clock against
last_invocationand only forwards a sample onceintervalhas elapsed (L728-733); otherwise it returns in nanoseconds. - pyi_floatclock, L22 — the timer used for
now. Windows usesQueryPerformanceCounter; the POSIX variant (L76) walks down fromCLOCK_MONOTONICthroughCLOCK_REALTIMEtogettimeofday. - build_call_stack, L305 — walks
f_backfrom leaf to root, appends a synthetic<thread>frame (L327), and joins the function, file and line fields with NUL bytes into one interned string per frame. - build_frame_tree, L22 — replays the recorded
(stack, time)pairs in a single pass, reusing matching stack prefixes and appending[self]leaf frames for time that belongs to no child. - default_processors, L307 — the eight-step shaping chain every frame-based renderer runs before writing output, from hiding importlib frames to grouping library code.
- ProfilerMiddleware, L37 — the Django integration: a profiler starts in
process_request, andprocess_responsewrites one report file per request.
The detail view: the same shape as the overview, with internals exposed — the AST transformer behind the IPython magic, the ProfilerState struct, the context-var watch, resampling, and the JSON web app behind the HTML report.
Why sampling, not tracing
A tracing profiler pays a tax on every call. A sampling profiler pays a tax every interval seconds, no matter how manic the call rate is — that is the whole pitch, and the design follows from it. Profiler.start() does not install anything itself; it records a start time, a start CPU time, and the current call stack as the start_call_stack, then subscribes to the thread’s sampler (profiler.py L118-169). From that point, samples arrive as (call_stack, time_since_last_sample) tuples appended to an ActiveProfilerSession buffer (L23-39). stop() wraps the buffer into a Session — duration, sample count, CPU time, sys.path snapshot and all (L193-205).
The Session object (session.py L23) is the unit of storage. It round-trips to disk as JSON — the .pyisession format (L68-75) — and Session.combine() concatenates two sessions’ records so that restarting a profiler produces one continuous report (L113-141). Nothing in a Session interprets the data; that is deferred to render time, when root_frame() replays the records through build_frame_tree (L147-163) and trims the boring stem of frames between interpreter entry and your start() call (L165-183).
The sampling loop lives in C
Everything timing-critical sits in pyinstrument/low_level/. The extension compiles from three sources — stat_profile.c, pyi_floatclock.c and pyi_timing_thread.c — into one module named pyinstrument.low_level.stat_profile (setup.py L13-22). The heart is the ProfilerState struct (stat_profile.c L35-46): the target callback, the interval, last_invocation, the context var to watch, an await_stack_list, an optional timer function, and which float clock to use.
The profile() callback is registered for eight event kinds — call, exception, line, return, c_call, c_exception, c_return, and pyinstrument’s own context_changed (L199-206). Each invocation grabs the time, checks whether the context var flipped (synthesizing a context_changed event for the Python layer when it did, L657-685), maintains the await stack by watching for coroutine returns via the co_flags & 0x80 bit (L693-701), and finally applies the interval gate at L728. Four timer types exist (L194-197): plain walltime, the shared walltime_thread, a user-supplied timer_func, and walltime_coarse. The Python layer picks the cheapest safe option: if the coarse clock’s resolution is finer than your interval, it wins (stack_sampler.py L163-167); if the precise clock costs more than 300 nanoseconds per call, pyinstrument warns you and suggests --use-timing-thread (L237-286), which hands timing to a background thread so the profiled program never calls the OS clock at all.
This is also where async support lives. CPython offers profilers no native notion of awaiting, so pyinstrument watches a ContextVar (stack_sampler.py L49-51) — the same mechanism async frameworks use to track tasks. When a sample arrives from outside the subscriber’s context, the sampler records what the subscriber was doing when it last awaited and files the time as an [await] frame under the awaiting function (profiler.py L269-280); in strict mode, foreign-context work collapses into an explicit [out-of-context] frame instead of polluting your report.
From frame_records to a rendered tree
Raw samples are a chronological log; a flame-style report needs a tree. build_frame_tree (frame_ops.py L22-77) does this in one pass: for each record it walks the recorded identifiers, reusing the existing node while the stack matches the previous sample and creating new Frame nodes at the first divergence. Self time is tracked by extending the last [self] leaf rather than adding a node per sample (L61-71), which matters when millions of samples flow through. Synthetic identifiers are declared in frame.py L21-24: [await], [self], [out-of-context] and the dummy [root].
The tree you want to look at is not the tree you captured, so eight processors reshape it (processors.py). remove_importlib (L25) and remove_tracebackhide (L41) delete noise; aggregate_repeated_calls (L59) converts the timeline into a time-sorted summary by merging siblings with identical identifiers and re-sorting children by total time (L79); remove_irrelevant_nodes (L191) drops anything under 1% of total time (L211); group_library_frames_processor (L84) folds library code into expandable FrameGroup objects, guided by hide_regex/show_regex and the is_application_code heuristic that treats anything under a sys.prefix as library code (frame.py L212-242); and remove_first_pyinstrument_frames_processor (L226) trims the CLI’s own __main__, eval and runpy frames. The chain is data, not code: FrameRenderer.preprocess just folds each processor over the root (renderers/base.py L111-115), and show_all or timeline simply delete processors from the list (L85-103).
One profiler, seven renderers
The renderer registry (renderers/init.py) exports ConsoleRenderer, HTMLRenderer, JSONRenderer, PstatsRenderer, SessionRenderer and SpeedscopeRenderer, all over a shared base. The console renderer draws the ASCII banner you know from the terminal — recorded time, duration, sample count, CPU time (console.py L91-121) — then walks the shaped tree with box-drawing characters or plain ASCII. The JSON renderer goes the other way: it emits minimal session JSON plus a frame tree serialized by hand (Frame.to_json_str, frame.py L373-388, inlined precisely because the json module costs two stack frames per level and deep stacks hit the recursion limit).
The HTML renderer is the most engineered. Sessions above 100,000 samples are resampled to a coarser interval — automatically chosen as duration / 10000 — doubling until the count fits (html.py L73-90). Session.resample (session.py L238-259) rounds each sample’s duration down to whole intervals, carrying remainders forward, so aggregate time stays honest while the timeline view loses granularity. The rendered HTML embeds a bundled Svelte application (the built app.js/app.css ship in html_resources/), which powers the timeline and call-stack views you interact with in the browser. The CLI ties it together: -r picks a renderer, the output file extension guesses one for you (guess_renderer_from_outfile, main.py L599-618), and every console report is saved as a .pyisession you can reopen with --load-prev, with the report folder pruned to the last ten files (L639-655).
From Django request to IPython cell
Three integrations share the same core. The Django middleware (middleware.py) starts a profiler in process_request when ?profile is in the query string or PYINSTRUMENT_PROFILE_DIR is configured (L38-56), then renders one file per request in process_response, with a filename template of {total_time:.3f}s {path} {timestamp:.0f}.{ext} (L61-103). If you serve Django locally, this is the fastest path from “the page is slow” to a flame view of exactly that request.
The IPython integration reuses the CLI’s option parser (compute_render_options, imported at magic.py L18) and installs an AST transformer around the cell: recent IPython versions get ReplaceCodeTransformer, which wraps your code in try/finally start/stop calls (L70-84), older versions get a pre/post AST pair (L54-68). Async cells run on a fresh loop in a separate thread (L295-326), and a dedicated processor strips IPython’s internal frames from the output (L329-357). Load it with %load_ext pyinstrument — IPython calls the load_ipython_extension hook in __init__.py (L13-19) — then prefix any cell with %%pyinstrument. The plain CLI wraps your script with runpy and disables async mode, since it profiles the whole program anyway (L393-397).
Honest Limits
Sampling means short functions can be missed entirely: a call that always finishes between two 1 ms ticks contributes no samples, and Enjoyed this post? Never miss out on future posts by following us interval trades resolution against overhead and memory (the CLI documents this trade-off on its -i flag, main.py L256-268). Sampling is per-thread by design — the StackSampler lives in thread_locals (stack_sampler.py L25, L292-302), so background threads appear only as their <thread> frames inside captured stacks, and start/stop must happen on the same thread or unsubscribe raises SubscriberNotFound. The C extension targets CPython’s PyEval_SetProfile API specifically; the pure-Python stat_profile_python.py exists to prototype the semantics and says so itself — it is “not used in normal execution” (L90-93). The HTML renderer’s 100,000-sample ceiling is real: past it, auto-resampling quietly coarsens your timeline. And Session.combine concatenates records from separate runs (session.py L113-141), so combined sessions work as aggregate summaries but not as timelines. None of these are bugs — they are the explicit cost model of a profiler whose headline virtue is that it barely perturbs the program it watches.