Portable measurement of execution time

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;
    public:
        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 thoughts on “Portable measurement of execution time

    1. 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

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>