Measuring execution time of a function in C++

Xara picture Xara · Mar 13, 2014 · Viewed 193.5k times · Source

I want to find out how much time a certain function takes in my C++ program to execute on Linux. Afterwards, I want to make a speed comparison . I saw several time function but ended up with this from boost. Chrono:

process_user_cpu_clock, captures user-CPU time spent by the current process

Now, I am not clear if I use the above function, will I get the only time which CPU spent on that function?

Secondly, I could not find any example of using the above function. Can any one please help me how to use the above function?

P.S: Right now , I am using std::chrono::system_clock::now() to get time in seconds but this gives me different results due to different CPU load every time.

Answer

Victor picture Victor · Mar 13, 2014

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();
    function();
    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!