Skip to content

Instantly share code, notes, and snippets.

@gongzhitaao
Last active January 28, 2024 14:25
Show Gist options
  • Save gongzhitaao/7062087 to your computer and use it in GitHub Desktop.
Save gongzhitaao/7062087 to your computer and use it in GitHub Desktop.
Simple high resolution timer in C++

A simple Timer class that provides satisfying resolution.

API

  • Timer() constructs the timer.
  • .reset() resets the timer
  • .elapsed() returns elapsed seconds in double since last reset.
#include <iostream>
#include <ctime>
class Timer
{
public:
Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }
double elapsed() {
clock_gettime(CLOCK_REALTIME, &end_);
return end_.tv_sec - beg_.tv_sec +
(end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
}
void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }
private:
timespec beg_, end_;
};
// Example code
int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;
tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}
#include <iostream>
#include <chrono>
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const {
return std::chrono::duration_cast<second_>
(clock_::now() - beg_).count(); }
private:
typedef std::chrono::high_resolution_clock clock_;
typedef std::chrono::duration<double, std::ratio<1> > second_;
std::chrono::time_point<clock_> beg_;
};
// Example code
int main()
{
Timer tmr;
double t = tmr.elapsed();
std::cout << t << std::endl;
tmr.reset();
t = tmr.elapsed();
std::cout << t << std::endl;
return 0;
}
@salkj
Copy link

salkj commented Oct 22, 2015

In the c++03 version, are you adding the seconds and the nanoseconds representation together? If so, isn't that just representing double the time elapsed?

@h3ct0rjs
Copy link

Thanks this was help very helpful.

@gongzhitaao
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment