Boost logo

Boost :

From: michel.andre_at_[hidden]
Date: 2001-03-22 05:14:19

I have written a small package consisting of a stop_watch class and
several counter classes for timing (mostly the various timers on
Windows NT GetTickCount, QueryPerformanceCounter, mmTimer and the

They look something like this:

#include <time.h>
#include <iostream>

template <typename COUNTER>
struct stop_watch
    typedef double diff_type;
    ///< The type used to express differences in seconds
    typedef COUNTER::tick_type tick_type;
    ///< Type used to express Ticks in seconds

    stop_watch(const COUNTER& counter = COUNTER()) : counter_(counter)
    { reset(); }

    void start()
        if (start_ != -1)
            throw "Timer already started";
        start_ = counter_.tick_count();

    // stops timer throws exception if timer
    // isn't started
    void stop()
        tick_type tick = counter_.tick_count();
        if (start_ == -1) throw "Timer not started";
        elapsed_ += (tick - start_);
        start_ = -1;

    // resets elapsed time and start time
    void reset()
        start_ = -1;
        elapsed_ = 0;

    // returns total elapsed time between last
    diff_type elapsed() const
        tick_type diff = (start_ == -1) ? 0 :
            counter_.tick_count() - start_;
        return diff_type(
            static_cast<diff_type>(elapsed_ + diff)/
    tick_type start_;
    tick_type elapsed_;
    COUNTER counter_;

// And the counter class using time.h clock function
struct clock_counter
    typedef clock_t tick_type;
    static tick_type ticks_per_sec()
        return CLOCKS_PER_SEC;
    static tick_type tick_count()
        return clock();

// Sample usage
int main(int argc, char* argv[])
        stop_watch<clock_counter> watch;
        // Lengty op
        std::cout << "Elapsed:" << watch.elapsed() ;
        std::cout << " secs" << std::endl;
        return 0;

It's now a fairly simple approach but i think its possible to build
something among those lines wich could be quite extensible. What i
have noticed with my several counter classes that i have is that
performance can differ greatly ie the overhead of using the timer.
And of course the resolution differs.

Could this be something to build on?

I would be interested in contributing to this kind of project.


Boost list run by bdawes at, gregod at, cpdaniel at, john at