Programming Search⌘K

Conceptcore

CPU profiling

Also called profiling, profiler, execution profile, sampling profiler, instrumenting profiler, deterministic profiling, flame graph.

A CPU profiler measures where a running program spends its processor time. It samples the call stack at intervals or counts each call, and reports the result per function or per path.

Applies to
core-languages

Idea

A program is slow, and the developer must decide what to change. A guess is often wrong, and a change in the wrong place costs time and adds risk. A profiler measures the program while it runs and reports where the processor time went: per function, per line or per path of calls.

A CPU profile answers two kinds of questions. The first is about time: which functions used most of the processor? The second is about counts: how many times did each function run? The gprof paper names both kinds. Counts show if an algorithm does what the developer expected, and a count that is too high can show an error in the algorithm. Counts are not proportional to time, because one call can take much longer than another.3

There are two methods to collect the data:

  • An instrumenting profiler adds code at each call and each return. It sees every call, so it knows the exact counts. Python's documentation calls this deterministic profiling.1
  • A sampling profiler stops the program at intervals and records where it is. It does not see every call. It gives a statistical picture of where the time goes, at a lower cost.1 3

The examples on this page print only counts and fixed facts. A time changes on each run, so a page that printed times would not have a fixed output.

How it works

Instrumentation

The instrumenting profiler needs a hook at the entry and the exit of each function. There are three ways to get it:

  • The compiler inserts it. The gprof compilers inserted a call to a monitoring routine in the prologue of each routine. The monitoring routine found its caller from the return address and counted each arc of the call graph, from a call site to a routine.3 GCC and gprof still use the option -pg for this.4 With -finstrument-functions, GCC calls __cyg_profile_func_enter and __cyg_profile_func_exit with the address of the current function and its call site.5
  • The interpreter provides it. Python calls a profile function at each call and each return, so cProfile needs no change to the code.1 sys.setprofile installs such a function from Python code.2
  • The programmer writes it. A wrapper function, a decorator or a scope guard counts each call. The examples in JavaScript, TypeScript, C++, Rust and C# use this method.

A profiler must not write a line of output at each call. The gprof paper says the volume of data would be too large, and the time to write it would be larger than the time of the program. The monitoring routine keeps a table of counts in memory and writes it when the program ends.3

The C example uses the GCC hooks. Each hook receives the address of a function, and a table maps addresses to counts:

fib(15) = 610
sum_squares(10) = 385
calls: main 1, fib 1973, sum_squares 1, square 10

Sampling

A sampling profiler sets a timer. At each tick it records the program counter, or the whole call stack, of the running thread. The gprof paper describes the method: the profile infers the time of each routine from the distribution of the samples. The method is "inherently a statistical approximation". The intervals must be uniform, and the program must run for enough intervals for the distribution to be accurate. The gprof system took a sample of the program counter at each clock tick, 1/60 of a second.3

A flame graph needs a profiler that samples whole stack traces, not only the program counter.7 These profilers do:

Profiler Default rate
Go runtime/pprof 100 samples a second, through the signal SIGPROF 10
Node.js --cpu-prof (V8) one sample each 1000 microseconds 13
JDK Flight Recorder one sample each 20 ms with the default settings, each 10 ms with profile (see the Java example)
Linux perf record the rate that -F gives; Gregg's examples use -F 99 7 8

The Go source explains its choice. Operating systems cannot send the signal at more than about 500 Hz, and the processing of each signal is not cheap, mostly because it gets the stack trace. 100 Hz gives useful data without a large load on the system, and it is a round number that converts sample counts to seconds.10 Gregg uses 99 Hz and 199 Hz on purpose. An odd rate does not sample in lockstep with other periodic activity, which would give misleading results.7

A sample does not know how many times a function was called. It only knows that the function was on the stack at that moment.7 The examples in Go, Java and JavaScript therefore count calls with their own counter and use the profiler only to show its API.

Flame graphs

A profile of a large program has many thousands of distinct stacks. A text report of them can fill many screens.7 Brendan Gregg made the flame graph to show all of them at once. It is made in three steps: capture stacks, fold them, and draw the folded stacks with flamegraph.pl.7 A folded stack is one line: the names of the frames from the bottom up, joined with ;, and a count. The Python example produces this format with sys.setprofile:

main 1
main;check 1
main;load 1
main;load;check 3
main;load;parse 3

In the drawing, each box is a frame. The y-axis is the depth of the stack. The top box is the function that was on the CPU, and the boxes below it are its callers. The x-axis is the population of samples, sorted in alphabetical order. It is not time. A wider box was present in more samples.6 7 The sort merges the frames of equal paths into one wide box, so the main paths stand out.7

A flame chart looks similar but puts time on the x-axis. The Chrome web inspector added flame charts, inspired by flame graphs.6

In languages

LanguageVerdictNote
PythonStandard library
C++Library
JavaStandard library
CLibrary
C#Library
JavaScriptStandard library
TypeScriptStandard library
GoStandard library
RustLibrary
KotlinStandard libraryKotlin on the JVM runs under JDK Flight Recorder and uses the jdk.jfr API, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no call stack to profile; the database server explains and measures the plan of a query instead.
BashIdiomThe shell has no profiler; the time keyword measures one pipeline, and a tool outside the shell samples the processes that a script starts.
PowerShellIdiomMeasure-Command measures the time of a script block; there is no profiler that samples the call stacks of a script; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup does not run code to profile.
CSSDoes not applyA style sheet does not run code to profile.
Regular expressionsDoes not applyA pattern has no functions to profile.
Language Verdict Form
Python stdlib cProfile and profile count every call; pstats sorts the results; sys.setprofile for a custom profiler
Go stdlib runtime/pprof samples at 100 Hz; go test -cpuprofile; net/http/pprof for a server
Java stdlib JDK Flight Recorder: the jdk.jfr API and -XX:StartFlightRecording
JavaScript stdlib Node.js --cpu-prof and the Profiler domain of node:inspector
TypeScript stdlib the profiler of the JavaScript engine
C library perf, gprof with -pg, and the compiler hooks of -finstrument-functions
C++ library as C; a scope guard for manual counts
Rust library perf and other tools outside the language; a Drop guard for manual counts
C# library dotnet-trace outside the program; [CallerMemberName] for manual counts
Kotlin stdlib JDK Flight Recorder on the JVM, as in Java
Bash, PowerShell idiom the shell can time a command but has no profiler of the call stacks
SQL, Regex, HTML, CSS n/a no call stack to profile

Python

cProfile and profile are deterministic profilers: they record all call, return and exception events. cProfile is a C extension with reasonable overhead. profile is written in Python and adds significant overhead.1 The ncalls column shows two numbers for a recursive function. In the example, 1973/1 means 1973 calls in all, of which one was a primitive call, a call that was not caused by recursion.1 The example reads the counts from pstats.Stats and prints no times.

The generator expression in total shows 400 calls for 100 calls of total. A profile function receives the event call when a function is called "or some other code block entered".2 Each resume of the generator enters its code again.

Go

pprof.StartCPUProfile(w) starts the sampler. The profile is buffered and written to w, and StopCPUProfile returns only after all the writes are complete.9 10 The result is a gzip-compressed protocol buffer for the pprof tool.9 The documentation shows three ways to collect a profile: go test -cpuprofile cpu.prof, a flag in main, and the HTTP handlers of net/http/pprof for a running server. go tool pprof cpu.prof reads the result.9

Java

JDK Flight Recorder is a framework that collects events from the application, the JVM and the operating system. java -XX:StartFlightRecording starts it from the command line.11 The jdk.jfr API starts and stops a recording from the program. A Configuration holds the settings of a recording, and the JDK ships two: default and profile.12 The example reads the sampling period of the event jdk.ExecutionSample from each one and prints whether the recording has events. The number of samples changes from run to run.

JavaScript and TypeScript

Node.js has the V8 CPU profiler. node --cpu-prof starts it when the program starts and writes the profile to a file before the program exits.13 The node:inspector module sends the commands Profiler.enable, Profiler.start and Profiler.stop to the same profiler from inside the program.14 The JavaScript example prints the field names of the profile, because the samples change on each run. TypeScript runs on the same engine. Its example writes a generic wrapper that keeps the type of the function that it wraps.

C, C++, Rust and C#

The C and C++ standards have no profiler. A tool outside the language does the work. perf record runs a command and records its profile in the file perf.data. The option -F sets the frequency and -g records the call stacks.8 gprof needs the program compiled and linked with -pg.4 The GCC option -finstrument-functions calls the two hooks at each entry and exit, and the attribute no_instrument_function excludes a function, such as the hooks themselves.5

Rust has no profiler in its standard library, and perf samples a Rust program as it samples a C program. .NET has dotnet-trace, which collects traces of a running process without a native profiler.15 The C++, Rust and C# examples count calls by hand. C++ and Rust use a guard object whose destructor pops the frame, which is RAII. C# uses [CallerMemberName], so the compiler passes the name of each function to the counter.

PythonGitHub
import cProfile
import pstats


def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


def price(item):
    return {"apple": 30, "bread": 250}.get(item, 0)


def total(cart):
    return sum(price(item) for item in cart)


def work():
    fib(15)
    for _ in range(100):
        total(["apple", "bread", "apple"])


profiler = cProfile.Profile()
profiler.runcall(work)
stats = pstats.Stats(profiler)

# Each key is (file, line, function). Each value starts with the number of
# primitive calls and the number of all calls. Print counts, not times.
print(f"{'function':<10} {'ncalls':>9}")
for (file, line, name), (primitive, calls, *_times) in sorted(stats.stats.items(), key=lambda kv: kv[0][2]):
    if file == __file__:
        shown = f"{calls}/{primitive}" if calls != primitive else str(calls)
        print(f"{name:<10} {shown:>9}")
Output
function      ncalls
<genexpr>        400
fib           1973/1
price            300
total            100
work               1

A profiler that counts calls can also count paths. sys.setprofile calls a function at each call and each return. The tracer below keeps a stack of names and counts each path. The result is the folded format that flame graph tools read.

import sys
from collections import Counter

stack = []
folded = Counter()


def tracer(frame, event, arg):
    """Records each call as a path of function names, the input of a flame graph."""
    if event == "call":
        stack.append(frame.f_code.co_name)
        folded[";".join(stack)] += 1
    elif event == "return":
        stack.pop()


def parse(line):
    return line.split(",")


def check(fields):
    return all(fields)


def load(lines):
    return [check(parse(line)) for line in lines]


def main():
    load(["a,b", "c,d", "e,"])
    check(["x"])


sys.setprofile(tracer)
main()
sys.setprofile(None)
for path, count in sorted(folded.items()):
    print(path, count)
Output
main 1
main;check 1
main;load 1
main;load;check 3
main;load;parse 3

Profile.run and cProfile.run take a string of code. It runs the string in the namespace of the module __main__, not in the namespace of the caller. A local variable of the caller is not visible. runctx takes the namespaces as arguments, and runcall takes a function.

This code raises NameError, on purpose.

import cProfile


def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)


def main():
    n = 20
    print("profiling fib(n) with n =", n)
    profiler = cProfile.Profile()
    profiler.run("fib(n)")  # the string runs in the namespace of __main__


main()
Output
profiling fib(n) with n = 20
  • Verdict: stdlib. cProfile and profile are deterministic profilers: they record every call and every return.
  • pstats.Stats sorts and prints the results. A count such as 1973/1 means 1973 calls, of which 1 was a primitive call, not a recursive call.
  • The examples print only call counts. The times change on each run.
  • python -m cProfile -s cumtime script.py profiles a whole script from the command line.
#include <map>
#include <print>
#include <string>
#include <vector>

// Manual instrumentation: a Scope object at the top of a function records the
// path of calls that led to it, one line per path, as a flame graph expects.
class Scope {
  public:
    explicit Scope(const char *name) {
        stack().push_back(name);
        std::string path;
        for (const auto &frame : stack()) {
            path += (path.empty() ? "" : ";") + frame;
        }
        folded()[path]++;
    }
    ~Scope() { stack().pop_back(); }
    Scope(const Scope &) = delete;
    Scope &operator=(const Scope &) = delete;

    static std::map<std::string, int> &folded() {
        static std::map<std::string, int> counts;
        return counts;
    }

  private:
    static std::vector<std::string> &stack() {
        thread_local std::vector<std::string> frames;
        return frames;
    }
};

std::vector<std::string> split(const std::string &line) {
    Scope scope("split");
    std::vector<std::string> fields{""};
    for (char c : line) {
        if (c == ',') {
            fields.emplace_back();
        } else {
            fields.back().push_back(c);
        }
    }
    return fields;
}

bool check(const std::vector<std::string> &fields) {
    Scope scope("check");
    for (const auto &field : fields) {
        if (field.empty()) {
            return false;
        }
    }
    return true;
}

int load(const std::vector<std::string> &lines) {
    Scope scope("load");
    int good = 0;
    for (const auto &line : lines) {
        good += check(split(line));
    }
    return good;
}

int main() {
    {
        Scope scope("main");
        std::println("good lines: {}", load({"a,b", "c,d", "e,"}));
        check({"x"});
    }
    for (const auto &[path, count] : Scope::folded()) {
        std::println("{} {}", path, count);
    }
}
Output
good lines: 2
main 1
main;check 1
main;load 1
main;load;check 3
main;load;split 3
  • Verdict: library. C++ has no profiler in the standard library. Tools outside the language, such as perf and gprof, sample or count the compiled program, as for C.
  • The Scope object uses RAII: the constructor pushes a frame and the destructor pops it, also when the function returns early.
  • The output is the folded format of flame graph tools: a path of names and a count on each line.
JavaGitHub
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import jdk.jfr.Configuration;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordingFile;

public class Main {
    static long fibCalls = 0;

    static int fib(int n) {
        fibCalls++;
        return n < 2 ? n : fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) throws Exception {
        // The JDK ships two settings files for Flight Recorder.
        for (String name : List.of("default", "profile")) {
            Configuration config = Configuration.getConfiguration(name);
            System.out.println(name + ": jdk.ExecutionSample every "
                + config.getSettings().get("jdk.ExecutionSample#period"));
        }

        Path file = Files.createTempFile("fib", ".jfr");
        try (Recording recording = new Recording(Configuration.getConfiguration("profile"))) {
            recording.start();
            System.out.println("fib(25) = " + fib(25));
            recording.stop();
            recording.dump(file);
        }
        List<RecordedEvent> events = RecordingFile.readAllEvents(file);
        Files.delete(file);
        // The number of samples depends on timing, so print only whether there are events.
        System.out.println("recording has events: " + !events.isEmpty());
        System.out.println("fib calls: " + fibCalls);
    }
}
Output
default: jdk.ExecutionSample every 20 ms
profile: jdk.ExecutionSample every 10 ms
fib(25) = 75025
recording has events: true
fib calls: 242785
  • Verdict: stdlib. JDK Flight Recorder is in the JDK. The jdk.jfr API starts and stops a recording from the program, and -XX:StartFlightRecording starts one from the command line.
  • The event jdk.ExecutionSample is a snapshot of a thread that executes Java code. The two settings files of the JDK, default and profile, sample at different periods.
  • The number of samples depends on timing, so the example prints only whether there are events. The call counter is manual instrumentation.
#include <stdio.h>

// With -finstrument-functions the compiler calls these two hooks at the entry
// and the exit of each function. The hooks must not be instrumented themselves.
#define MAX_FUNCS 8
static void *funcs[MAX_FUNCS];
static long counts[MAX_FUNCS];

__attribute__((no_instrument_function)) void __cyg_profile_func_enter(void *fn, void *site) {
    (void)site;
    for (int i = 0; i < MAX_FUNCS; i++) {
        if (funcs[i] == fn || funcs[i] == NULL) {
            funcs[i] = fn;
            counts[i]++;
            return;
        }
    }
}

__attribute__((no_instrument_function)) void __cyg_profile_func_exit(void *fn, void *site) {
    (void)fn;
    (void)site;
}

static int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

static int square(int x) { return x * x; }

static int sum_squares(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += square(i);
    }
    return sum;
}

__attribute__((no_instrument_function)) static long count_of(void *fn) {
    for (int i = 0; i < MAX_FUNCS; i++) {
        if (funcs[i] == fn) {
            return counts[i];
        }
    }
    return 0;
}

int main(void) {
    printf("fib(15) = %d\n", fib(15));
    printf("sum_squares(10) = %d\n", sum_squares(10));
    printf("calls: main %ld, fib %ld, sum_squares %ld, square %ld\n", count_of((void *)main), count_of((void *)fib),
           count_of((void *)sum_squares), count_of((void *)square));
}
Output
fib(15) = 610
sum_squares(10) = 385
calls: main 1, fib 1973, sum_squares 1, square 10
  • Verdict: library. The C standard has no profiler. GCC and Clang insert calls to two hooks with -finstrument-functions, and tools outside the language do the rest: perf samples the stacks on Linux, and gprof reads the counts of a program built with -pg.
  • The hooks receive the address of each function. A table maps addresses to counts, and the program compares them with the addresses of its own functions.
  • The GCC manual suggests the attribute no_instrument_function for the hooks, so that the compiler does not instrument them.
using System.Runtime.CompilerServices;

Console.WriteLine($"fib(20) = {Work.Fib(20)}");
Console.WriteLine($"total = {Work.Total(["apple", "bread", "apple"])}");
foreach (var (name, count) in Calls.Counts.OrderBy(kv => kv.Key, StringComparer.Ordinal))
{
    Console.WriteLine($"{name,-6} {count,6}");
}

static class Calls
{
    public static readonly Dictionary<string, int> Counts = new();

    // The compiler fills in the name of the calling method.
    public static void Count([CallerMemberName] string name = "")
    {
        Counts[name] = Counts.GetValueOrDefault(name) + 1;
    }
}

static class Work
{
    public static int Fib(int n)
    {
        Calls.Count();
        return n < 2 ? n : Fib(n - 1) + Fib(n - 2);
    }

    public static int Price(string item)
    {
        Calls.Count();
        return item == "bread" ? 250 : 30;
    }

    public static int Total(string[] cart)
    {
        Calls.Count();
        return cart.Sum(Price);
    }
}
Output
fib(20) = 6765
total = 310
Fib     21891
Price       3
Total       1
  • Verdict: library. The base library has no profiler API. The dotnet-trace tool collects traces of a running process from outside the program. It uses EventPipe, a part of the .NET runtime.
  • [CallerMemberName] makes the compiler pass the name of the calling method, so the counter needs no string in each function.
  • A Dictionary has no fixed order, so the example sorts the names before it prints them.
JavaScriptGitHub
const { Session } = require("node:inspector");

// Instrumentation: wrap a function so that each call is counted.
const counts = new Map();
function counted(name, fn) {
  return function (...args) {
    counts.set(name, (counts.get(name) ?? 0) + 1);
    return fn.apply(this, args);
  };
}

const fib = counted("fib", (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)));

// Sampling: the V8 CPU profiler through the inspector protocol.
const session = new Session();
session.connect();
session.post("Profiler.enable", () => {
  session.post("Profiler.start", () => {
    const result = fib(25);
    session.post("Profiler.stop", (err, { profile }) => {
      console.log("fib(25) =", result);
      console.log("profile fields:", Object.keys(profile).sort().join(", "));
      console.log("root node:", profile.nodes[0].callFrame.functionName);
      console.log("fib calls:", counts.get("fib"));
      session.disconnect();
    });
  });
});
Output
fib(25) = 75025
profile fields: endTime, nodes, samples, startTime, timeDeltas
root node: (root)
fib calls: 242785
  • Verdict: stdlib. Node.js runs the V8 CPU profiler through node:inspector, and node --cpu-prof writes a profile of the whole program before it exits.
  • The profile is a tree of nodes with a call frame each, plus a list of samples and the time between them. The example prints only the field names, because the samples change on each run.
  • A wrapper function counts calls. It is instrumentation by hand, and it adds a call to each call.
TypeScriptGitHub
// Instrumentation: traced() wraps a function and records the path of calls
// that led to each call, one line per path, as a flame graph expects.
const stack: string[] = [];
const folded = new Map<string, number>();

function traced<A extends unknown[], R>(name: string, fn: (...args: A) => R): (...args: A) => R {
  return (...args: A): R => {
    stack.push(name);
    const path = stack.join(";");
    folded.set(path, (folded.get(path) ?? 0) + 1);
    try {
      return fn(...args);
    } finally {
      stack.pop();
    }
  };
}

const parse = traced("parse", (line: string): string[] => line.split(","));
const check = traced("check", (fields: string[]): boolean => fields.every((f) => f !== ""));
const load = traced("load", (lines: string[]): number => lines.filter((line) => check(parse(line))).length);
const main = traced("main", (): void => {
  console.log("good lines:", load(["a,b", "c,d", "e,"]));
  check(["x"]);
});

main();
for (const [path, count] of [...folded].sort(([a], [b]) => (a < b ? -1 : 1))) {
  console.log(path, count);
}
Output
good lines: 2
main 1
main;check 1
main;load 1
main;load;check 3
main;load;parse 3
  • Verdict: stdlib. TypeScript runs on a JavaScript engine and uses its profiler: node --cpu-prof or node:inspector, as in the JavaScript example.
  • The generic traced keeps the parameter types and the return type of the function that it wraps, so the wrapped function has the same type.
  • finally pops the stack also when the function throws.
package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"runtime/pprof"
)

var calls = map[string]int{} // instrumentation: a counter in each function

func fib(n int) int {
	calls["fib"]++
	if n < 2 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

func main() {
	var buf bytes.Buffer
	if err := pprof.StartCPUProfile(&buf); err != nil {
		fmt.Println("start:", err)
		return
	}
	fib(25)
	pprof.StopCPUProfile() // the profile is complete only after Stop

	// The profile is a gzip-compressed protocol buffer.
	zr, err := gzip.NewReader(&buf)
	if err != nil {
		fmt.Println("not gzip:", err)
		return
	}
	data, _ := io.ReadAll(zr)
	fmt.Println("profile is gzip:", true)
	fmt.Println("profile has data:", len(data) > 0)
	fmt.Println("fib calls:", calls["fib"])
}
Output
profile is gzip: true
profile has data: true
fib calls: 242785

StartCPUProfile buffers the profile and writes it to the writer. The profile is complete only after StopCPUProfile. A program that returns without the call leaves an empty file.

This code runs but gives a wrong answer on purpose.

package main

import (
	"bytes"
	"fmt"
	"runtime/pprof"
)

func fib(n int) int {
	if n < 2 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

func main() {
	var buf bytes.Buffer
	pprof.StartCPUProfile(&buf)
	fib(25)
	fmt.Println("bytes before Stop:", buf.Len()) // the profile is still empty
}
Output
bytes before Stop: 0
  • Verdict: stdlib. runtime/pprof samples the call stacks of the program 100 times a second and writes a gzip-compressed protocol buffer.
  • The number of samples depends on timing, so the example prints only facts that do not change. The call counter is manual instrumentation.
  • go test -cpuprofile cpu.prof profiles the tests and benchmarks of a package. go tool pprof cpu.prof reads the result.
  • net/http/pprof serves the profiles of a running server over HTTP.
RustGitHub
use std::cell::RefCell;
use std::collections::BTreeMap;

thread_local! {
    static STACK: RefCell<Vec<&'static str>> = const { RefCell::new(Vec::new()) };
    static FOLDED: RefCell<BTreeMap<String, u64>> = const { RefCell::new(BTreeMap::new()) };
}

/// Manual instrumentation: a Scope records the path of calls that led to it,
/// one line per path, as a flame graph expects. Drop pops the frame.
struct Scope;

impl Scope {
    fn enter(name: &'static str) -> Scope {
        let path = STACK.with_borrow_mut(|stack| {
            stack.push(name);
            stack.join(";")
        });
        FOLDED.with_borrow_mut(|folded| *folded.entry(path).or_insert(0) += 1);
        Scope
    }
}

impl Drop for Scope {
    fn drop(&mut self) {
        STACK.with_borrow_mut(|stack| stack.pop());
    }
}

fn fib(n: u32) -> u64 {
    let _scope = Scope::enter("fib");
    if n < 2 { n as u64 } else { fib(n - 1) + fib(n - 2) }
}

fn square(x: u64) -> u64 {
    let _scope = Scope::enter("square");
    x * x
}

fn main() {
    {
        let _scope = Scope::enter("main");
        println!("fib(4) = {}", fib(4));
        println!("square(fib(5)) = {}", square(fib(5)));
    }
    FOLDED.with_borrow(|folded| {
        for (path, count) in folded {
            println!("{path} {count}");
        }
    });
}
Output
fib(4) = 3
square(fib(5)) = 25
main 1
main;fib 2
main;fib;fib 4
main;fib;fib;fib 8
main;fib;fib;fib;fib 8
main;fib;fib;fib;fib;fib 2
main;square 1
  • Verdict: library. The Rust standard library has no profiler. A tool outside the language, such as perf on Linux, samples a compiled Rust program as it samples a C program.
  • Drop pops the frame when the guard goes out of scope, also on an early return and on a panic that unwinds.
  • BTreeMap keeps the paths sorted, so the output has a fixed order.

Wall time and CPU time

A CPU profile shows the time that a thread spent on the processor. A thread that waits for a disk, a lock or the network is not on the CPU, so a CPU profile does not show the wait. Gregg's page lists off-CPU flame graphs as a separate kind for this time.6 The JDK describes its event jdk.ExecutionSample, in the output of jfr metadata, as a snapshot of a thread that executes Java code. Threads that wait or execute native code are not in it.

Profiling and debugging

A profile can also find bugs. Python's documentation says that call counts can identify bugs in code, through "surprising counts".1 A function that runs 1973 times for fib(15) shows exponential Recursion without memoization. Interactive debugging shows the state of one moment. A profile summarizes the whole run.

Tracing

A tracer records each event with its time, in order. A profiler adds the events up. Gregg first traced each CPU function call of MySQL and drew the calls with time on the x-axis. The overhead of tracing was too high, so he switched to timed sampling.6

Pitfalls

The profiler changes the program

An instrumenting profiler runs extra code at each call. Python's documentation warns that the profilers add overhead to Python code but not to C functions, so C code looks faster than any Python code. The profilers are for an execution profile, not for benchmarks; timeit is for benchmarks.1

Counts are not time

gprof assumed that all calls to a routine take the same time. The paper warns that this assumption can hide a call site whose calls are always faster or slower than the average.3 A function with a high count may be cheap, and a function with a count of 1 may hold most of the time.

Short runs and odd rates

A sampling profiler needs enough samples. At 100 Hz, a run of half a second gives about 50 samples, and a function that ran for 5 ms may have none.3 10 A rate that matches a periodic task in the program samples the same phase of that task each time. Gregg uses 99 Hz for this reason.7

Broken stacks

A sampler walks the stack with the frame pointer. Many compilers, GCC among them, omit the frame pointer as an optimization. The flame graph then misses towers. Gregg gives two fixes: compile with -fno-omit-frame-pointer, or install debug information with DWARF data and use the DWARF stack walker of perf.7 A JIT compiler causes a second problem. The JVM compiles methods at run time and has no symbol table for a system profiler, so perf shows hexadecimal addresses for Java methods.7

The profile is not complete

StartCPUProfile buffers the profile. Until StopCPUProfile returns, the writer may have nothing in it.9 A program that exits without the call leaves an empty file. The Go wrong example prints the size of the buffer before StopCPUProfile: 0 bytes.

The code runs in another namespace

cProfile.run(command) executes the string in the namespace of the module __main__. A local variable of the caller is not in that namespace, and the Python example fails with NameError. runctx takes the global and local namespaces as arguments, and Profile.runcall takes a function and its arguments.1

Cost

The cost of an instrumenting profiler grows with the number of calls. The cost of a sampling profiler grows with the rate, and samples that are too frequent overwhelm the program.3 Python's documentation says that statistical profiling traditionally has less overhead, because the code needs no instrumentation.1

Some published numbers:

  • gprof added five to thirty percent to the execution time of the program.3
  • Python says deterministic profiling adds only a small overhead in typical applications, because the interpreter already adds so much.1
  • JEP 328 set a success metric of at most 1% overhead for Flight Recorder with the default settings on the SPECjbb2015 benchmark, and no measurable overhead when it is not enabled.11

A profiler also needs memory. A counter per function or per arc is small.3 A sampler stores one stack per sample, so a long run at a high rate makes a large file. The folded format adds equal stacks together, so its size depends on the number of distinct paths.7

History

For calls to monitoring routines, the gprof paper cites the prof command of the Unix Programmer's Manual of January 1979.3 Graham, Kessler and McKusick at Berkeley wrote gprof while they worked on a code generator. They presented it at the SIGPLAN '82 Symposium on Compiler Construction. gprof added the call graph: it charged the time of each routine to the routines that called it.3

Brendan Gregg invented flame graphs when he worked on a performance problem in MySQL. Function tracing slowed the target too much, so he sampled instead. Sampling has gaps, so the order in time was lost. He sorted the samples to merge equal frames. The warm colors suggested hot CPUs, and the picture looked like flames. He released flame graphs in December 2011.6

References

  1. Python documentation, The Python Profilers, Introduction to the profilers (and its Note); Instant User's Manual (ncalls); Reference Manual (run, runctx, Profile.runcall); What Is Deterministic Profiling?; Limitations
  2. Python documentation, sys, System-specific parameters and functions, sys.setprofile
  3. Susan L. Graham, Peter B. Kessler and Marshall K. McKusick, gprof, a Call Graph Execution Profiler, Proceedings of the SIGPLAN '82 Symposium on Compiler Construction, 1982, pages 120 to 126 (read from the copy at https://docs-archive.freebsd.org/44doc/psd/18.gprof/paper.pdf), 2 Types of Profiling; 3 Gathering Profile Data; 3.1 Execution Counts; 3.2 Execution Times; 7 Conclusions
  4. GNU gprof manual, Compiling a Program for Profiling, section 2
  5. GCC manual, Program Instrumentation Options, -finstrument-functions
  6. Brendan Gregg, Flame Graphs, Summary; Variations (flame charts); Origin; Updates
  7. Brendan Gregg, CPU Flame Graphs, 1.1 Too Much Data; 3 Description; 4 Instructions; 4.1 Linux perf; 4.3 DTrace; 6 C; 8.1 Background
  8. Linux manual page, perf-record(1), NAME; OPTIONS (-F, -g, --call-graph)
  9. Go standard library, package runtime/pprof, Profiling a Go program; StartCPUProfile; StopCPUProfile; Profile.WriteTo
  10. Go source, runtime/pprof/pprof.go, StartCPUProfile (the comment on the sampling rate and the constant hz)
  11. JEP 328, Flight Recorder, the summary; Success Metrics; Description (the command line and the configuration sets)
  12. Java SE 25 API, jdk.jfr.Configuration, the class description; getConfiguration; getDescription
  13. Node.js documentation, Command-line API, --cpu-prof; --cpu-prof-interval
  14. Node.js documentation, Inspector, CPU profiler
  15. .NET documentation, dotnet-trace performance analysis utility, the introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/YNFMX3/text.yaml