This guide shows you how to measure execution time of code blocks or functions using the scoped and manual profiling classes.
1. Understand the Profiling Classes
CSimProfiler and CSimScopeProfiler provide a lightweight, high-resolution profiling mechanism for measuring execution time of code blocks or functions. They use std::chrono::steady_clock by default for monotonic and reliable time measurements, and allow integration with a running average collector.
- CProfilerType — a template wrapper to easily define the clock type for profiling. Defaults to
std::chrono::steady_clock. - CSimScopeProfiler — RAII-style scoped profiler. Automatically measures the time between construction and destruction of the object.
- CSimProfiler — manual profiler. You explicitly call
Start()andEnd()to measure execution duration.
2. Profile a Short-Lived Block with CSimScopeProfiler
Use the scoped profiler for short-lived blocks of code. Its constructor records the start time, and its destructor calculates the elapsed time and optionally updates a running average.
- Create a
CSimScopeProfilerinstance at the start of the scope you want to measure, passing a name and an optional running-average pointer. - Let it go out of scope naturally — elapsed time is measured and reported automatically.
{
CSimScopeProfiler simScopeProfiler("ItemName", &runningAverage);
// Do work...
// When simScopeProfiler goes out of scope, elapsed time is automatically measured and reported.
}
Members:
| Member | Description |
|---|---|
| simulationNANOSec | Timestamp when the profiler starts (using ClockT). |
| text | Name of the profiled code section. |
| runningAverage | Pointer to a CRunningAverage object to accumulate measurements. |
3. Profile Manually with CSimProfiler
Use the manual profiler when you need explicit control over start and end points.
- Call
Start()at the beginning of the section to measure. - Do the work you want to time.
- Call
End("ItemName")to report the elapsed time. - Optionally call
Append("ItemName", runningAverage)to update a running average manually.
CSimProfiler profiler;
profiler.Start();
// Do some work...
profiler.End("ItemName"); // Reports elapsed time
profiler.Append("ItemName", runningAverage); // Updates running average manually
4. Choose the Right Profiler for the Job
- Use
CSimScopeProfilerwhen the measured region maps cleanly to a code scope (a block, function, or loop iteration) — it requires no manual bookkeeping. - Use
CSimProfilerwhen start and end points do not align with a single scope, or when you need to control exactly when the measurement is appended to a running average.