Measuring time durations

Today on the poul‘s mailing list someone asked: “How to measure the time spent in a function?”. I replied with the code that I use for that purpose, but later I thought that it was an interesting question, so I’m posting the solution here on the blog.

The solution is to use the boost date_time library. It is simple, portable (works on Linux, Win and Mac) and precise, since the time is printed in microseconds.

Here is an example code that shows how to profile a function:

#include <iostream>
#include <boost/date_time.hpp>

void f()
{
 for(volatile int i=0;i<100000;i++) ;
}

int main()
{
 using namespace std;
 using namespace boost::posix_time;

 ptime t1(microsec_clock::local_time());
 f();
 ptime t2(microsec_clock::local_time());

 cout<<t2-t1<<endl;
}

Just replace f() with the function you want to profile. Of course you can profile the time spent running your entire program by putting the whole program between the declaration of t1 and t2.

The time is printed in this format:

./test
00:00:00.000620

To be able to compile the program, you need to link with the boost_system library. With the g++ compiler you must add -lboost_system when linking.

Of course you need to have the boost libraries installed. On Linux type:

sudo apt-get install libboost-dev libboost-thread-dev

While on Windows, get this compiler that comes with boost precompiled.

About these ads

Tags: , ,

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


Follow

Get every new post delivered to your Inbox.

Join 29 other followers

%d bloggers like this: