Search code examples
c++optimizationprofiling

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.


Solution

  • 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 <chrono>
    
    /* Only needed for the sake of this example. */
    #include <iostream>
    #include <thread>
        
    void long_operation()
    {
        /* Simulating a long, heavy operation. */
    
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(150ms);
    }
    
    int main()
    {
        using std::chrono::high_resolution_clock;
        using std::chrono::duration_cast;
        using std::chrono::duration;
        using std::chrono::milliseconds;
    
        auto t1 = high_resolution_clock::now();
        long_operation();
        auto t2 = high_resolution_clock::now();
    
        /* Getting number of milliseconds as an integer. */
        auto ms_int = duration_cast<milliseconds>(t2 - t1);
    
        /* Getting number of milliseconds as a double. */
        duration<double, std::milli> ms_double = t2 - t1;
    
        std::cout << ms_int.count() << "ms\n";
        std::cout << ms_double.count() << "ms\n";
        return 0;
    }
    

    This will measure the duration of the function long_operation.

    Possible output:

    150ms
    150.068ms
    

    Working example: https://godbolt.org/z/oe5cMd