2011-06-30 35 views
2

我需要計算運行某個函數所需的時間並運行到以下代碼(來源:http://snippets.dzone.com/posts/show/4254),並聲明「...記錄&輸出執行時間爲在微秒一段代碼」需要在C中使用timeval結構的幫助

/* Put this line at the top of the file: */ 
#include <sys/time.h> 

/* Put this right before the code you want to time: */ 
struct timeval timer_start, timer_end; 
gettimeofday(&timer_start, NULL); 

/* Put this right after the code you want to time: */ 
gettimeofday(&timer_end, NULL); 
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec)/1000000.0; 
printf("Time spent: %.6f\n", timer_spent); 

,但我有一段代碼個人經驗表明,輸出‘時間’以秒爲單位,而不是微秒。我需要一些關於我是對還是錯的信息(我需要徹底澄清這一點)。

回答

2

你說得對。

tv_sec該結構的成員存儲秒,並且tv_usec成員(微秒)通過除以10^6轉換爲秒。

-1

修改這樣的:

double timer_spent = (timer_end.tv_sec - timer_start.tv_sec)*1e6 + (timer_end.tv_usec - timer_start.tv_usec); 
+0

不,你還必須乘以10^6的第一部分,將秒轉換爲微秒。 – sje397

+0

@ sje397確實。修正了,謝謝。 –

1

它提供以秒爲微秒的時間差(與下列術語:(timer_end.tv_usec - timer_start.tv_usec))。所以你應該沒問題:)

+0

雖然單位是秒。 – sje397

+0

是的,我想你是對的。似乎我誤解了這個問題。 – Constantinius