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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <iostream> #include <thread> #include <cmath> #include <cstdlib> #include <boost/timer/timer.hpp> using namespace std; using namespace boost::timer; int main() { srand((unsigned int)time(NULL)); auto_cpu_timer program_timer(3); auto procUser = [](long work) { for (long i = 0; i < work; ++i) sqrt(123.456L); }; auto procSystem = [](long work) { for (long i = 0; i < work; ++i) thread([](){}).detach(); }; auto procTimer = [](long work) { cpu_timer timer; timer.start(); for(long i = 0; i < work; ++i) rand(); timer.stop(); cout << "Thread timer:" << timer.format(3); }; thread t1(procUser, 1000000000); thread t2(procSystem, 100000); thread t3(procTimer, 100000000); t1.join(); t2.join(); t3.join(); cout << "Program timer:"; return 1; } |
Thread timer: 0.750s wall, 1.790s user + 0.850s system = 2.640s CPU (352.1%)
Program output.
Program timer: 3.171s wall, 5.080s user + 2.980s system = 8.060s CPU (254.2%)