Portable measurement of execution time

August 19th, 2009 § 2 Comments

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.

Tagged: ,

§ 2 Responses to Portable measurement of execution time

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>

What’s this?

You are currently reading Portable measurement of execution time at 0x.

meta