Click here to Skip to main content
15,886,026 members
Articles / CPU
Tip/Trick

Measuring CPU Time

Rate me:
Please Sign up or sign in to vote.
3.30/5 (3 votes)
16 Mar 2019MIT 4.7K   1  
How to measure CPU time?

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.

C++
#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;
}

Program output:

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%)
This article was originally posted at https://vorbrodt.blog/2019/03/16/measuring-cpu-time

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --