0

我在 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 上都试过这个程序。

4

1 回答 1

1

也许CLOCKS_PER_SEC=1000000在你的系统中。

所以按预期time_taken/CLOCKS_PER_SEC给出。0

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

于 2012-02-08T11:23:39.440 回答