Function execution time

I want to know the runtime of my function written in C ++ on Linux. I found a lot of posts about this. I tried all the methods mentioned in this Timer Methods link to calculate the time. The following are the results 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 my testimony, since all the results differ in testimony. I read that your OS switches between different tasks, so the readings may not be very accurate. Is there a way that I can just calculate the time spent on my function. I heard about the use of the profiling tool, but have not yet found an example for any function. Please guide me.

+2
source share
2

(7).

( , ) , .

, , , , . , ( time (1)...), , ( , , ).

, g++ -Wall -pg -O1 gprof (1) ( , oprofile...).

. ( Zara).

+2

, , , . :

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

}

, , benchmark0 benchmark1 : CPU, I/O..., / - , .

, g++ .

+1

Source: https://habr.com/ru/post/1694281/


All Articles