簡體   English   中英

time.h庫不起作用

[英]time.h library not working

我在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上都嘗試了該程序。

也許您的系統中的CLOCKS_PER_SEC=1000000

因此, time_taken/CLOCKS_PER_SEC給出預期的0

將您的代碼更改為double(time_taken)/CLOCKS_PER_SEC以獲取浮點數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM