2011-11-16 34 views
1

所以這是非常基本的,但我真的不知道C.獲取的時間量在C運行功能

我想找到的東西需要運行,沒有時鐘(CPU)週期的毫秒數。

我嘗試使用

struct timeval start,end; 
double dif; 

gettimeofday(&start, 0); 
//do stuff 
gettimeofday(&end, 0); 
dif = (end - start)/1000.0; 
printf("The time taken was %lf \n",dif); 

我收到的時候我嘗試編譯此錯誤:

bubble.c: In function ‘main’:
bubble.c:55: error: invalid operands to binary - (have ‘struct timeval’ and ‘struct timeval’)

回答

3

變化

dif = (end - start) * 1000; 

dif = (end.tv_sec - start.tv_sec) * 1000 
+ (end.tv_usec - start.tv_usec)/1000; 

在僞代碼:

Get the seconds part of the time delta 
Multiply by 1000 to get milliseconds 
Get the microseconds part of the time delta 
Divide that part by 1000 
Add that part to the milliseconds from seconds delta 
+0

完美,謝謝! – switz

+0

在大多數情況下,這應該可以正常工作。但我建議使用帶有「struct time_val」的timersub()來代替。 – paulsm4

+0

@moshbear - 你改變了我的帖子:)你目前的版本* *更*脆弱:) – paulsm4

0

爲了快速基準測試中,我會使用clock()CLOCKS_PER_SEC

下面是一些宏代碼我使用:

#define CLOCK_TICK(acc, ctr) ctr = std::clock() 
#define CLOCK_TOCK(acc, ctr) acc += (std::clock() - ctr) 
#define CLOCK_RESET(acc) acc = 0 
#define CLOCK_REPORT(acc) (1000. * double(acc)/double(CLOCKS_PER_SEC)) 

static clock_t t1a, t1c; 


int main() 
{ 
    while (true) 
    { 
    CLOCK_RESET(t1a); 
    init_stuff(); 
    CLOCK_TICK(t1a, t1c); 
    critical_function(); 
    CLOCK_TOCK(t1a, t1c); 

    std::cout << "This round took " << CLOCK_REPORT(t1a) << "ms.\n"; 
    } 
} 

你可以得到更高分辨率的時鐘出了新<chrono>頭的。宏應該直接適應。

1

你想:

dif = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1000.0; 

注1:您需要tv_sec來處理即使是短暫持續時間過一秒鐘。

注2:第二項除以1000.0,以便使用浮點數而不是整數除法。

+0

絕對正確。這就是爲什麼我建議使用moshbear原始帖子的timersub()。在他編輯之前,他建議「dif =(end.tv_usec - start.tv_usec)/ 1000;」,這在任何情況下都不適用。 – paulsm4

0

在Linux上,最好的方法是使用times(2)接口,而不是gettimeofday(2)讀取手冊頁。

man 2 times.

它具有精緻的保真度。