The C `clock()` function just returns a zero

只愿长相守 提交于 2019-11-26 11:14:08

问题


The C clock() function just returns me a zero. I tried using different types, with no improvement... Is this a good way to measure time with good precision?

#include <time.h>
#include <stdio.h>

int main()
{
    clock_t start, end;
    double cpu_time_used;

    char s[32];

    start = clock();

    printf(\"\\nSleeping 3 seconds...\\n\\n\");
    sleep(3);

    end = clock();

    cpu_time_used = ((double)(end - start)) / ((double)CLOCKS_PER_SEC);

    printf(\"start = %.20f\\nend   = %.20f\\n\", start, end);
    printf(\"delta = %.20f\\n\", ((double) (end - start)));
    printf(\"cpu_time_used  = %.15f\\n\", cpu_time_used);
    printf(\"CLOCKS_PER_SEC = %i\\n\\n\", CLOCKS_PER_SEC);

    return 0;
}
Sleeping 3 seconds...

start = 0.00000000000000000000
end   = 0.00000000000000000000
delta = 0.00000000000000000000
cpu_time_used  = 0.000000000000000
CLOCKS_PER_SEC = 1000000

Platform: Intel 32 bit, RedHat Linux, gcc 3.4.6


回答1:


clock() reports CPU time used. sleep() doesn't use any CPU time. So your result is probably exactly correct, just not what you want.




回答2:


man clock. It's not returning what you think it is. Also man gettimeofday - it's more likely what you want.




回答3:


clock_t is an integer type. You can't print it out with %f. See Fred's answer for why the difference is 0.




回答4:


 printf("start = %.20f\nend   = %.20f\n", start, end);

should be:

 printf("start = %d\nend   = %d\n", start, end);



回答5:


Calling sleep() isn't going to use up any CPU time. You should see a little difference, though. I corrected your printf type mismatch bug in this line:

printf("start = %.20f\nend   = %.20f\n", start, end);

And it gave reasonable results on my machine:

start = 1419
end   = 1485
delta = 66
cpu_time_used  = 0.000066000000000
CLOCKS_PER_SEC = 1000000

You might try gettimeofday() to get the real time spent running your program.




回答6:


You probably need

double get_wall_time(){ struct timeval time; if (gettimeofday(&time,NULL)){ return 0; } return (double)time.tv_sec + (double)time.tv_usec * .000001; } and usage something like

double wall0 = get_wall_time(); double cpu0 = get_cpu_time(); for(long int i = 0; i<=10000000;i++){ func1(); } double wall1 = get_wall_time(); double cpu1 = get_cpu_time(); cout << "Wall Time = " << wall1 - wall0 << endl; cout << "CPU Time = " << cpu1 - cpu0 << endl;

instead of clock()

as clock only and only counts time spent in CPU only based on performance counters. but you can get result by using above function. just to verify your application run it with time command

like time ./a.out

output of time command :

real 0m5.987s user 0m0.674s sys 0m0.134s

and output of custom function Wall Time = 5.98505 CPU Time = 0.8



来源:https://stackoverflow.com/questions/2134363/the-c-clock-function-just-returns-a-zero

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!