Skip to content

Instantly share code, notes, and snippets.

@mortenpi
Created April 28, 2014 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mortenpi/11365146 to your computer and use it in GitHub Desktop.
Save mortenpi/11365146 to your computer and use it in GitHub Desktop.
C++ Timer class using POSIX times()
#include "Timer.hh"
#include <iostream>
#include <sys/times.h>
#include <unistd.h>
// ---------------------------------------------------------------------
// class Time
// ---------------------------------------------------------------------
const long Time::sc_clk_tck = sysconf(_SC_CLK_TCK);
Time Time::now()
{
struct tms tms;
clock_t clock = times(&tms);
Time p;
p.clock = clock;
p.utime = tms.tms_utime;
p.stime = tms.tms_stime;
return p;
}
Time operator- (const Time &t1, const Time &t2)
{
Time t;
t.utime = t1.utime - t2.utime;
t.stime = t1.stime - t2.stime;
t.clock = t1.clock - t2.clock;
return t;
}
std::ostream& operator<< (std::ostream &out, const Time &p)
{
out << double(p.utime)/Time::sc_clk_tck << ' '
<< double(p.stime)/Time::sc_clk_tck << ' '
<< double(p.clock)/Time::sc_clk_tck;
return out;
}
// ---------------------------------------------------------------------
// class Timer
// ---------------------------------------------------------------------
Timer::Timer() : start(Time::now()) {}
Time Timer::elapsed()
{
return Time::now() - start;
}
#ifndef Timer_h
#define Timer_h
#include <ostream>
struct Time {
static const long sc_clk_tck;
long utime, stime, clock;
static Time now();
};
Time operator- (const Time &t1, const Time &t2);
std::ostream& operator<< (std::ostream &out, const Time &p);
class Timer {
public:
const Time start;
Timer();
Time elapsed();
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment