perf-cpp: Hardware Performance Monitoring for C++¶
perf-cpp lets you measure hardware performance counters for specific parts of your code — not the entire program.
Place start() and stop() around exactly the code you care about.
Tip
New to performance counters? Start with What are Hardware Performance Counters?
Count Hardware Events¶
Count instructions, cycles, cache misses, and more while your code runs:
#include <perfcpp/event_counter.hpp>
auto event_counter = perf::EventCounter{};
event_counter.add({"seconds", "instructions", "cycles", "cache-misses"});
event_counter.start();
code_to_profile(); /// <-- your code here
event_counter.stop();
const auto result = event_counter.result();
for (const auto [event_name, value] : result)
{
std::cout << event_name << ": " << value << std::endl;
}
→ Recording event statistics in detail
Sample Instructions and Memory Accesses¶
Record snapshots every N events — capturing instruction pointers, timestamps, memory addresses, cache levels, and more:
#include <perfcpp/sampler.hpp>
auto sampler = perf::Sampler{};
sampler.trigger("cycles", perf::Period{50000U});
sampler.values()
.timestamp(true)
.cpu_id(true)
.logical_instruction_pointer(true);
sampler.start();
code_to_profile(); /// <-- your code here
sampler.stop();
const auto samples = sampler.result();
samples.to_csv("samples.csv");
Next Steps¶
- Record events for a code region → Recording
- Find where events happen → Sampling
- Measure across threads or cores → Parallel Recording / Parallel Sampling
- Combine counters into ratios (CPI, miss rates) → Metrics
- Generate flamegraphs → Symbols & Flamegraphs