Skip to content
systemcoding.dev
Performance

Profile one function only with callgrind --toggle-collect

Count instructions only inside one function by passing --toggle-collect=compute to callgrind, so setup code stays out of the profile.

1 min read
Summarize in AI

Callgrind counts every instruction by default, so the code that builds your input drowns the function you want to study. --toggle-collect flips collection on when the named function is entered and off when it returns. Start with collection disabled so the first toggle is an "on".

c
// work.c
#include <stdio.h>
#include <stdlib.h>

long compute(const int *v, int n) {
    long s = 0;
    for (int i = 0; i < n; i++) s += v[i] * 3;
    return s;
}

int main(void) {
    int n = 1000000;
    int *v = malloc(n * sizeof *v);
    for (int i = 0; i < n; i++) v[i] = i % 7;
    printf("%ld\n", compute(v, n));
    free(v);
    return 0;
}
Shell
gcc -O1 -g -o work work.c
valgrind --tool=callgrind --collect-atstart=no --toggle-collect=compute ./work
Text
==5120== Callgrind, a call-graph generating cache profiler
8999991
==5120== Collected : 9000022

Only the instructions inside compute and its callees are in callgrind.out.5120, nine per loop iteration in this example, though the exact count depends on the compiler. The name is matched against the symbol, and a * wildcard is allowed. With inlining at higher optimisation levels the function may not exist as a symbol, so -O1 or __attribute__((noinline)) keeps it visible. Options are documented in the Callgrind manual, here for Valgrind 3.25. The run is far slower than native, so use a small input.

Also inDebugging
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.