Skip to content

Instantly share code, notes, and snippets.

@hacst
Created March 17, 2012 09:12
Show Gist options
  • Save hacst/2056936 to your computer and use it in GitHub Desktop.
Save hacst/2056936 to your computer and use it in GitHub Desktop.
Cross-platform, high-resolution time measurement using C++11's std::chrono
#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;
}
@Lamzin
Copy link

Lamzin commented Sep 15, 2015

Thanks for sharing!

@amorozov
Copy link

amorozov commented Oct 9, 2015

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