C `clock()` 函数只返回一个零

2021-12-23 00:00:00 time c c++ clock

C clock() 函数只返回零.我尝试使用不同的类型,但没有任何改进......这是一种以高精度测量时间的好方法吗?

#include #include int main(){clock_t 开始,结束;双 cpu_time_used;字符 [32];开始 = 时钟();printf("
睡眠 3 秒...

");睡眠(3);结束 = 时钟();cpu_time_used = ((double)(end - start))/((double)CLOCKS_PER_SEC);printf("start = %.20f
end = %.20f
", start, end);printf("delta = %.20f
", ((double) (end - start)));printf("cpu_time_used = %.15f
", cpu_time_used);printf("CLOCKS_PER_SEC = %i

", CLOCKS_PER_SEC);返回0;}

<块引用>

睡眠3秒...开始 = 0.00000000000000000000结束 = 0.00000000000000000000增量 = 0.00000000000000000000cpu_time_used = 0.000000000000000CLOCKS_PER_SEC = 1000000

平台:Intel 32 位,RedHat Linux,gcc 3.4.6

解决方案

clock() 报告 CPU 使用时间.sleep() 不使用任何 CPU 时间.所以你的结果可能完全正确,只是不是你想要的.

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("
Sleeping 3 seconds...

");
    sleep(3);

    end = clock();

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

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

", 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

解决方案

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

相关文章