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

标签 c++ c time clock

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

#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

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

最佳答案

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

关于c++ - C `clock()` 函数只返回一个零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2134363/

相关文章:

c - 优化级别打破了 C 代码顺序

c++ - C/C++ 类型定义/结构中的冗余命名

java - 计算耗时?

c++ - 在构建时指定模板参数

c++ - 将 QVector 指针作为参数传递

android - 使用 NDK 显示轮廓的图像处理

c - 0.00001 增量

php - 如何获得以微秒为单位的持续时间

php - 时间到日期转换

c++ - 更有效地迭代