Portable measurement of execution time

Posted on: 19/08/2009

Once in a while so it happens that a programmer wishes to time his own creation. This article presents a simple and portable implementation of a Timer class which saves the time of its creation and computes the time it took until destruction, effectively measuring the runtime spent in the enclosing scope.

// ----- header -----

#include <ctime>
#include <string>

class Timer {
        std::string m_name;
        std::clock_t m_started;
        Timer (const std::string &name = "undef");
        ~Timer (void);

// ----- source -----

#include <iostream>
using std::cout;
using std::endl;
using std::clock;

Timer::Timer (const std::string &name)
    : m_name(name), m_started(clock()) {
        // empty

Timer::~Timer (void) {
    double secs = static_cast<double>(clock() - m_started) / CLOCKS_PER_SEC;
    cout << m_name << ": " << secs << "secs." << endl;

Note that it’s possible that you will not get a fine enough resolution on your own system with this implementation, since it uses the portable API provided by ctime. If that’s the case you better look for a more precise, probably platform-specific, interface for retrieving timing information.

Here’s a simple usage example:

#include "Timer.h"

int main () {
    Timer timeit("useless double loop");
    volatile int ret = 3;

    for (int i=0;i<60000;++i)
        for (int j=0;j<60000;++j)
            ret += i | j;

    return ret;

And the output generated by this program on my lousy laptop:

antrikot:~/work/sandbox/timer> g++ -Wall -pedantic main.cc
antrikot:~/work/sandbox/timer> ./a.out
useless double loop: 14.62secs.


2 Responses to "Portable measurement of execution time"


Great post! I have two comments.

1. the compiler should kill both loops because x,i,j are unmodified. If you want to loop to remain, define them as volatile.

2. The pattern you used is RAII (http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization)

You are absolutly correct.

The RAII pattern also comes in pretty handy when locking mechanisms are in use, both for easily aquiring the lock and for making sure it’s released when going out of scope (even if an exception has occured).

Thanks alot for posting!

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: