Measuring how long your program ran for is easy with std::chrono, but what if you need details about user and system space time? Easy! Use Boost CPU Timer library 🙂 It’s another simple library from Boost with only few classes: auto_cpu_timer is like a RAII object; it starts the clock in its constructor, stops it in its destructor, and prints the elapsed time to standard output. cpu_timer class is for manual starting and stopping of the clock; it also allows you to retrieve the elapsed times (wall, user, and system) in nanoseconds.

In the below example I create three threads: procUser spends 100% of its time in the user space calling std::sqrt function. procSystem spawns a lot of threads causing transitions into the kernel. And procTimer is just an illustration of cpu_timer usage.

Thread timer: 0.750s wall, 1.790s user + 0.850s system = 2.640s CPU (352.1%)
Program timer: 3.171s wall, 5.080s user + 2.980s system = 8.060s CPU (254.2%)

Program output.

Leave a Reply