time.h库无法正常工作

时间:2012-02-08 11:17:22

标签: c time.h

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

1 个答案:

答案 0 :(得分:1)

您的系统中可能 CLOCKS_PER_SEC=1000000

所以 time_taken/CLOCKS_PER_SEC 会按预期提供 0

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