Cross-platform high-resolution timer

Often there is a need to estimate the time it takes for a piece of code to run. This is useful not only for debugging but also for reporting the execution time of lengthy tasks to the user.

On Windows, QueryPerformanceFrequency() and QueryPerformanceCounter() can be used to determine the execution time of a code. QueryPerformanceFrequency() returns the frequency of the current performance counter in counts per second and QueryPerformanceCounter() returns a high resolution (<1┬Ás) time stamp. Together they can be used to determine time it takes to run a piece of code is:

LARGE_INTEGER _frequency;
QueryPerformanceFrequency(&_frequency);

LARGE_INTEGER _start;
QueryPerformanceCounter(&_start);

// Code which takes a long time to run.

LARGE_INTEGER _stop;
QueryPerformanceCounter(&_stop);

double _intervalInSeconds = (_stop.QuadPart - _start.QuadPart) / _frequency.QuadPart;

On Linux, clock_gettime can be used to get a time interval with a resolution of nano-seconds. clock_gettime() requires two arguments: clockid_t and timespec structure. To build a timer, CLOCK_MONOTONIC is a good choice for clockid_t as the time is guaranteed to be monotonically increasing. timespec structure have two field: tv_sec (time in seconds) and tv_nsec (time in nanoseconds). Code to determine the time it takes to run a piece of code is:

struct timespec _start;
clock_gettime(CLOCK_MONOTONIC, &_start);

// Code which takes long time to run.

struct timespec _stop;
clock_gettime(CLOCK_MONOTONIC, &_stop);

double _intervalInseconds = (_stop.tv_sec + _stop.tv_nsec*1e-9) - (_start.tv_sec + _start.tv_nsec*1e-9);

I have written a simple class which can be user on both windows and Linux. It has the following interface:

class Timer
{
public:

    enum TimeUnit
    {
        TimeInSeconds = 1,
        TimeInMilliSeconds = 1000,
        TimeInMicroSeconds = 1000000
    };

public:

    Timer();
    ~Timer();

    // On Windows, returns true if high performance timer is available.
    // On Linux, always returns true.
    bool IsTimerAvailable();

    // Start the timer.
    void Start();

    // Stop the timer and return the time elapsed since the timer was started.
    double Stop(TimeUnit timeUnit = TimeInMilliSeconds);

    // Get the time elapsed since Start() was called.
    double TimeElapsedSinceStart(TimeUnit timeUnit = TimeInMilliSeconds);

    // Get the total time elapsed between Start() and Stop().
    double TotalTimeElasped(TimeUnit timeUnit = TimeInMilliSeconds);
};

You can download the code from the following links:
Timer.h
Timer.cpp
Timer_Unix.cpp
Timer.zip


No comments yet

Write a comment, your thoughts are welcome: