Created
March 17, 2012 09:12
-
-
Save hacst/2056936 to your computer and use it in GitHub Desktop.
Cross-platform, high-resolution time measurement using C++11's std::chrono
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> | |
#include <thread> | |
using namespace std; | |
using namespace chrono; | |
int main() | |
{ | |
cout << "Measurement resolution: " << | |
duration_cast<nanoseconds>(high_resolution_clock::duration(1)).count() | |
<< "ns" << endl; | |
cout << "Will now tell thread to sleep for 1ms and measure that in actual time" << endl; | |
auto start = high_resolution_clock::now(); | |
this_thread::sleep_for(milliseconds(1)); | |
auto end = high_resolution_clock::now(); | |
auto dur = duration_cast<nanoseconds>(end - start); | |
cout << "Measured time: " << dur.count() << "ns" << endl; | |
cout << "Delta: " << | |
duration_cast<nanoseconds>(dur - milliseconds(1)).count() | |
<< "ns" << endl; | |
return 0; | |
} |
I would use steady_clock instead of high_resolution_clock, since it's the only one which guarantees, well, steady timer. See this https://solarianprogrammer.com/2012/10/14/cpp-11-timing-code-performance/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing!