首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >time.h库不工作

time.h库不工作
EN

Stack Overflow用户
提问于 2012-02-08 19:17:22
回答 1查看 1.3K关注 0票数 0

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

问题是:

程序输出总是显示零秒,有时‘时钟’是交换的:

代码语言:javascript
复制
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)

该程序的目的是在速度方面比较这两个函数。我该如何比较呢?

下面是测试代码:

代码语言:javascript
复制
 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上都尝试过这个程序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-08 19:23:39

也许是你系统里的CLOCKS_PER_SEC=1000000

所以time_taken/CLOCKS_PER_SEC不出所料地给出了0

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9192269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档