-
-
Save tzutalin/fd0340a93bb8d998abb9 to your computer and use it in GitHub Desktop.
Simple high resolution timer in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
class Timer { | |
public: | |
Timer() : | |
m_beg(clock_::now()) { | |
} | |
void reset() { | |
m_beg = clock_::now(); | |
} | |
double elapsed() const { | |
return std::chrono::duration_cast<std::chrono::milliseconds>( | |
clock_::now() - m_beg).count(); | |
} | |
private: | |
typedef std::chrono::high_resolution_clock clock_; | |
typedef std::chrono::duration<double, std::ratio<1> > second_; | |
std::chrono::time_point<clock_> m_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