Timing algorithm: clock() vs time() in C++

后端 未结 5 850
失恋的感觉
失恋的感觉 2020-12-22 23:08

For timing an algorithm (approximately in ms), which of these two approaches is better:

clock_t start = clock();
algorithm();
clock_t end = clock();
double t         


        
5条回答
  •  一个人的身影
    2020-12-22 23:28

    The time_t structure is probably going to be an integer, which means it will have a resolution of second.

    The first piece of code: It will only count the time that the CPU was doing something, so when you do sleep(), it will not count anything. It can be bypassed by counting the time you sleep(), but it will probably start to drift after a while.

    The second piece: Only resolution of seconds, not so great if you need sub-second time readings.

    For time readings with the best resolution you can get, you should do something like this:

    double getUnixTime(void)
    {
        struct timespec tv;
    
        if(clock_gettime(CLOCK_REALTIME, &tv) != 0) return 0;
    
        return (tv.tv_sec + (tv.tv_nsec / 1000000000.0));
    }
    
    double start_time = getUnixTime();
    double stop_time, difference;
    
    doYourStuff();
    
    stop_time = getUnixTime();
    difference = stop_time - start_time;
    

    On most systems it's resolution will be down to few microseconds, but it can vary with different CPUs, and probably even major kernel versions.

提交回复
热议问题