Xara Xara - 1 month ago 17
C++ Question

Measuring execution time of a function in C++

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

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>

using namespace std;
using namespace std::chrono;

void function()
{
    long long number = 0;

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

int main()
{
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    function();
    high_resolution_clock::time_point t2 = high_resolution_clock::now();

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

    cout << duration;
    return 0;
}

This will measure the duration of the function.

NOTE: It is not a requirement to get the same output always because the CPU of your machine can be less or more used by other processes running on your computer. As you would solve a math exercise, your mind can be more or less concentrated so you will solve that in different times. In the human mind, we can remember the solution of a math problem, though for a computer the same process will always be something new, so, as I Said, it is not required to get the same result always!