gpt4 book ai didi

c - time.h 库不工作

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

我正在学习 K&R 书和练习 3-1。我认为我的“time.h”库坏了。起初我以为我的代码是错误的,但是当我检查练习的解决方案时在网络上,它们也不起作用。

问题:

程序输出始终显示零秒,并且“时钟”有时会交换:

Output 1:
Element -1 not found.
binsearch() took 10000 clocks (0 seconds)
Element -1 not found.
binsearch2() took 20000 clocks (0 seconds)

Output 2:
Element -1 not found.
binsearch() took 20000 clocks (0 seconds)
Element -1 not found.
binsearch2() took 10000 clocks (0 seconds)

该程序的目的是比较两个函数的速度。我该如何比较?

这是测试代码:

 for ( i = 0, time_taken = clock(); i < 100000; ++i ) {
index = binsearch(n, testdata, MAX_ELEMENT); /* all this code is duplicated with a
} call to binsearch2 instead */
time_taken = clock() - time_taken;

if ( index < 0 )
printf("Element %d not found.\n", n);
else
printf("Element %d found at index %d.\n", n, index);

printf("binsearch() took %lu clocks (%lu seconds)\n",
(unsigned long) time_taken,
(unsigned long) time_taken / CLOCKS_PER_SEC);

我在 Linux 和 Windows 中都尝试过这个程序。

最佳答案

您的系统中可能有CLOCKS_PER_SEC=1000000

因此,time_taken/CLOCKS_PER_SEC 给出了预期的 0

将代码更改为 double(time_taken)/CLOCKS_PER_SEC 以获取浮点。

关于c - time.h 库不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9192269/

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