Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Simple high resolution timer in C++

View timer-c++03.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#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;
}
View timer-c++03.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.