Time programs in C++

This is a summary of exploration of timing functions in C++

clock() only gives you CPU time. So if your program runs in parallel in a cluster it might not work. Even running on parallel multi-core computer, it it not accurate. (Also, if you sleep(), then it will not record the time).

In order to record “ELAPSED TIME”, we need to gettimeofday. time() only gives you time in seconds. I needed more precise measurement. gettimeofday() gives you microseconds.

The code that does the timing looks like the following

#include <time.h>

#include <iostream>       // std::cout, std::endl

#include <thread>         // std::this_thread::sleep_for

#include <chrono>         // std::chrono::seconds

#include <unistd.h>

#include <sys/time.h>

//this would measure elapsed time but on the granularity of seconds

using namespace std;

int main()


struct timeval startTV, endTV;

gettimeofday(&startTV, NULL);

//code goes here

std::chrono::milliseconds dura( 5120 );

std::this_thread::sleep_for( dura );

gettimeofday(&endTV, NULL);

long seconds = endTV.tv_sec - startTV.tv_sec;

long useconds = endTV.tv_usec - startTV.tv_usec;

long mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf("%ld micro seconds elapsed\n", mtime);

return 0;


A good reference stack overflow post


The final example that I followed


This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s