5

I want to find out the execution time of my function written in C++ on Linux. I found lots of posts regarding that. I tried all the methods mentioned in this link Timer Methods for calculating time. Following are the results of execution time of my function:

time() :           0 seconds 
clock() :          0.01 seconds
gettimeofday() :   0.002869 seconds
rdtsc() :          0.00262336 seconds
clock_gettime() :  0.00672151 seconds
chrono :           0.002841 seconds 

Please help me which method is reliable in its readings as all the results differ in their readings. I read that your OS is switching between different tasks so the readings cannot be expected to be very accurate. Is there a way that I can just calculate the time CPU spends on my function. I heard about the use of profiling tool but have not found any example for just a function yet. Please guide me.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Xara
  • 8,748
  • 16
  • 52
  • 82

2 Answers2

2

Read time(7).

For various reasons (and depending upon your actual hardware, i.e. your motherboard) the time is not as accurate as you want it to be.

So, add some loop repeating your function many times, or change its input so that it runs longer. Ensure that the execution time of the total program (given by time(1)...) is at least a second approximately (if possible, ensure that you have at least half a second of CPU time).

For profiling, compile and link with  g++ -Wall -pg -O1 then use gprof(1) (there are more sophisticated ways to profile, e.g. oprofile ...).

See also this answer to a very similar question (by the same Zara).

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

If you are doing simple test, trying to find out which implementation is better, then any method is okay. For example:

const int MAX = 10000;             // times to execute the function

void benchmark0() {
    auto begin = std::chrono::steady_clock::now();

    for (int i = 0; i < MAX; ++i)
        method0();

    auto now = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - begin);
    std::cout << "Cost of method0() is " << elapsed .count() << " milliseconds" << std::endl;
}

void benchmark1() { /* almost the same as benchmark0, but calls method1 */ }

int main() {

    benchmark0();
    benchmark0();

    benchmark1();
    benchmark1();

}

You might have noticed benchmark0 and benchmark1 has been called consecutively twice: because there will be cache of CPU, I/O ..., you might want to get rid of the performance gain/lost due to caching, but measure the pure execution time.

Of course, you can also use g++ to profile the program.

Xin
  • 1,300
  • 2
  • 14
  • 27