Timing the execution of a function in C++11

There are some nice C++11 APIs available to measure the execution times of a function(s). The library of interest here is <chrono>. It provides some basic methods to obtain timing information from the CPU. I generally use the following pattern to determine timing information for my code:

const int maxIterations = 1000000;

// obtain the current time to mark as the start
std::chrono::high_resolution_clock::time_point startTime = 
  std::chrono::high_resolution_clock::now();

// do something
launch(0, maxIterations);

// obtain the current time to mark as the end 
std::chrono::high_resolution_clock::time_point endTime = 
  std::chrono::high_resolution_clock::now();

// compute the elapsed time
auto elapsedTime = 
  std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();

std::cout << "Elapsed time: " << elapsedTime << std::endl;

See the C++ documentation for other methods included in the chrono library.

Leave a Reply

Your email address will not be published. Required fields are marked *