Thomas Sampson

C++ High Resolution Timer


Intro #

Some basic code to perform high-resolution performance measurements in C++ using the <chrono> library.
 

Code #

GitHub Gist: https://git.io/JJ3xz

//------------------------------------------------------------------------------------------------------------------------------

#include <iostream>
#include <chrono>

//------------------------------------------------------------------------------------------------------------------------------

int main()
{
// Start timer
auto start = std::chrono::high_resolution_clock::now();

//--------------------------------------------------------------------------------------------------------------------------
// [YOUR CODE HERE]
//--------------------------------------------------------------------------------------------------------------------------

// Stop timer
auto end = std::chrono::high_resolution_clock::now();
auto duration = (end - start);
auto us = std::chrono::duration_cast<std::chrono::microseconds>(duration); // Microsecond (as int)
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration); // Milliseconds (as int)
const float ms_fractional = static_cast<float>(us.count()) / 1000; // Milliseconds (as float)
std::cout << "Duration = " << us.count() << "µs (" << ms_fractional << "ms)" << std::endl;
}

//-------------------------------------------------------