【发布时间】:2012-02-08 11:17:22
【问题描述】:
我在 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 上都试过这个程序。
【问题讨论】:
-
不,不是它。如果您建议将迭代次数降低到 10-20k,则输出将变为“0 个时钟”且仍为 0 秒。
-
抱歉,打错了。相反,您需要将迭代次数增加一个很大的倍数(至少与
CLOCKS_PER_SEC一样多)。