简体   繁体   English

time.h库不起作用

[英]time.h library not working

I am on the K&R book and on exercise 3-1. 我在K&R书上,并在练习3-1中。 I think my "time.h" library is broken. 我认为我的“ time.h”库损坏了。 At first I thought my code was wrong but when I checked the solutions to the exercise on the net, they don't work either. 刚开始我以为我的代码是错误的,但是当我在网上检查该练习的解决方案时,它们也不起作用。

The problem: 问题:

The program output always shows zero seconds and the 'clocks' are sometimes are exchanged: 程序输出始终显示零秒,有时会交换“时钟”:

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)

The purpose of the program is to compare the two functions in terms of speed. 该程序的目的是比较两个功能的速度。 How do I compare this? 我该如何比较?

Here is the test code: 这是测试代码:

 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);

I tried this program in both Linux and Windows. 我在Linux和Windows上都尝试了该程序。

Maybe CLOCKS_PER_SEC=1000000 in your system. 也许您的系统中的CLOCKS_PER_SEC=1000000

So time_taken/CLOCKS_PER_SEC gives 0 as expected. 因此, time_taken/CLOCKS_PER_SEC给出预期的0

Change your code to double(time_taken)/CLOCKS_PER_SEC to get floating-point. 将您的代码更改为double(time_taken)/CLOCKS_PER_SEC以获取浮点数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM