#include #include /// *nix - headers, wont work with win32 so far #include class Timer { public : /// return time in secs virtual double operator()() const = 0; }; /// how much cpu-time wasted? class CPULoadTimer : public Timer { public: double operator()() const { return static_cast(clock()) / static_cast(CLOCKS_PER_SEC); } }; /// *nix - based, wont work with win32 so far class MicroSecsTimer : public Timer { public: MicroSecsTimer() { gettimeofday(&m_tv, &m_tz); }; double operator()() const { gettimeofday(&m_tv, &m_tz); return (static_cast(m_tv.tv_sec) * 1000000.0 + static_cast(m_tv.tv_usec)) * 0.000001; } private: mutable struct timeval m_tv; mutable struct timezone m_tz; }; template class StopWatch { public: StopWatch(const TimerType& timer) : m_timer(timer), m_start(0), m_stop(0) { }; void start() { m_start= currentTime(); } void stop() { m_stop= currentTime(); } double duration() const { return (m_stop > m_start ? m_stop - m_start : 0); } double currentTime() const { return m_timer(); } std::ostream& print(std::ostream& os) const { return os << "[" << m_start << "] => [" << m_stop << "]"; } private: const TimerType& m_timer; double m_start; double m_stop; }; template std::ostream& operator<<(std::ostream& os, const StopWatch sw) { return sw.print(os); } int main() { CPULoadTimer cpuloadtimer; StopWatch cpuloadwatch(cpuloadtimer); cpuloadwatch.start(); for(unsigned i= 0; i < 10000000; i++ ) { }; cpuloadwatch.stop(); std::cout << cpuloadwatch << " : " << cpuloadwatch.duration() << std::endl; MicroSecsTimer micro; StopWatch microwatch(micro); microwatch.start(); for(unsigned i= 0; i < 10000000; i++ ) { }; microwatch.stop(); std::cout << microwatch << " : " << microwatch.duration() << std::endl; return 0; }