gpt4 book ai didi

c - 使用clock()获取C程序中耗时

转载 作者:行者123 更新时间:2023-11-30 15:15:14 27 4
gpt4 key购买 nike

我一直在尝试使用时钟函数测量 C 程序中耗时,但每当我尝试 printf 任何时钟值时,我都会返回 0。例如:

    clock_t time1, time2;
time1 = clock();
printf("Time 1 is %d.\n", (int)time1);
sleep(2);
time2 = clock();
printf("Time 2 is %d.\n", (int)time2);

在这两种情况下,time1 和 time2 都打印为 0。我有一种感觉,这是因为我在 printf 中使用了错误的类型,但我见过的每种类型似乎都不适合我。我用过%Lf、%ld、%f。其他人能发现这里有问题吗?

编辑:我尝试了此线程中提到的大多数类型:What’s the correct way to use printf to print a clock_t?我什至尝试了 uintmax_t,但无法打印 p1 和 p2,我不知道如何验证这是否是类型问题或者时钟是否没有返回足够的值。

最佳答案

来自cplusplus.com

Clock program Returns the processor time consumed by the program.

The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).

The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.

基本上,如果您的计算时间太短,您将不会注意到任何事情。

尝试添加一个从 0 到较大值的 while 循环,并在第二次调用 clock() 之前增加其中的 volatile 变量。

关于c - 使用clock()获取C程序中耗时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694962/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com