【问题标题】:time.h library not workingtime.h 库不工作
【发布时间】: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 一样多)。

标签: c time.h


【解决方案1】:

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

所以 time_taken/CLOCKS_PER_SEC 给了 0 符合预期。

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

【讨论】:

  • 很可能,posix 要求 CLOCKS_PER_SEC=1000000。 @1der,不,没有。将时钟滴答转换为毫秒而不是秒。 (注意,clock() 在 linux 和 windows 上是不同的。在 linux 上,clock() 测量 CPU 时间,在 windows 上它测量挂钟时间)
  • 你们俩都是对的,它们都在几分之一秒内完成,并且因为输出被格式化为整数,所以它被截断为零。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2015-06-06
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多