2016-03-02 82 views
1

我想測量代碼的和平執行時間。
我用clock()函數做它。
這裏的例子:用Windows在C中測量執行時間

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <time.h> 

int main(void) { 
    clock_t begin=0, end=0; 

    begin = clock(); 
    printf("hello world!!\n"); 
    end = clock(); 

    printf("Begin %E\n",begin); 
    printf("End %E\n",end); 
    printf("Clocks %E\n",end-begin); 
    printf("Clocks per second %E\n", CLOCKS_PER_SEC); 
    printf("Time %E\n", (end-begin)/CLOCKS_PER_SEC); 

    return 0; 
} 

這裏輸出:

hello world!! 
Begin 2.529616E-320 
End 2.535545E-320 
Clocks 5.928788E-323 
Clocks per second 4.940656E-318 
Time 0.000000E+00 

時間爲0!
我在做什麼錯了? 輸出是否正確?

非常感謝

+0

它小於皮秒。我認爲這是不可能在windows ... –

+1

測量單個printf語句的執行時間是毫無意義的。 – pranav

+1

[使用printf打印時鐘的正確方法\ _t?]的可能重複(http://stackoverflow.com/questions/1083142/what-s-the-correct-way-to-use-printf-to -print-a-clock -t) –

回答

6

%E需要浮點(floatdouble)。要發送整數值

要拆分確保數是浮動

(端開始+ 0.0)/ CLOCKS_PER_SEC);

+0

非常感謝!你是對的! –

+0

'(double)(end-begin)'也可以 – Magisch