Skip to content
Create a gist now

Instantly share code, notes, and snippets.

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

Thanks for sharing!

@amorozov

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
Something went wrong with that request. Please try again.