Measuring execution time of a function in C++

The Solution to Measuring execution time of a function in C++ is

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from <chrono> header.

Use it like so:

#include <iostream>
#include <chrono>

void function()
    long long number = 0;

    for( long long i = 0; i != 2000000; ++i )
       number += 5;

int main()
    auto t1 = std::chrono::high_resolution_clock::now();
    auto t2 = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration;
    return 0;

This will measure the duration of the function.

NOTE: You will not always get the same timing for a function. This is because the CPU of your machine can be less or more used by other processes running on your computer, just as your mind can be more or less concentrated when you solve a math exercise. In the human mind, we can remember the solution of a math problem, but for a computer the same process will always be something new; thus, as I said, you will not always get the same result!

~ Answered on 2014-03-13 18:30:14

Most Viewed Questions: