Linux下的函式執行時間的統計方法

2021-06-06 10:18:20 字數 2074 閱讀 9407

原址

如何測試某個函式的執行時間是做實驗時經常用到的功能,在此比較linux下的測試函式,主要是其精確度。我們採用統一的測試標準程式(standard.c):

#include

#define max 1000 /* the loop count */

/* function: do loop operation

* input: null

* output: counter->the counter result

*/int do_work()

int main()

通過命令gcc -o standard standard.c生成測試程式。

linux下的方法:

(1) 使用命令time:

[root@localhost-120 xgf]# time ./standard

counter = 1000000

real 0m0.006s

user 0m0.000s

sys 0m0.000s

time命令對秒(s)級別的很精確,而對毫秒級的誤差比價大。我們可以通過sleep/usleep函式來進行測試。sleep(0.1)或者usleep(100)都是表示休眠100ms,而測試結果都是:

real 0m0.002s

user 0m0.000s

sys 0m0.000s

(2) 通過difftime函式:

double difftime(time_t time1, time_t time0);計算time1和time0之間的秒數。測試程式如下:

#include

#include

#define max 1000

int do_work()

int main()

測試結果如下:

val = 0.000000

real 0m0.006s

user 0m0.000s

sys 0m0.000s

我們發現,difftime的精確度還沒有time命令高。

(3) 通過gettimeofday函式:

int gettimeofday(struct timeval *tv, struct timezone *tz); 其中timeval結構定義如下:

struct timeval

;獲取當前時刻,可以精確到微妙級別。

#include

#include

#define max 1000 /* the loop count */

/* function: do loop operation

* input: null

* output: counter->the counter result

*/int do_work()

int main()

輸出結果如下:

interval = 3.527000

real 0m0.006s

user 0m0.000s

sys 0m0.000s

也就是3.527ms。

(4) 利用rdtsc彙編指令,這是硬體計數器提供的功能,可以精確到1/f(f為處理器頻率)。

#include

#include

#define max 1000

#define frequence 1595984000.00 /* the frequence of cpu */

int do_work()

int main()

輸出結果如下:

start_high: 00013272 start_low: a1081568

end_high: 00013272 end_low: a1600586

lost time is: 57f01e 3.611002

real 0m0.006s

user 0m0.000s

sys 0m0.000s

綜上所述,time命令和difftime函式基本都是秒級別的,根本達不到毫秒級別的計數。而gettimeofday和rdtsc是很精確的方式,建議如果大家以後需要毫秒級別的計數採用gettimeofday或者rdtsc。

Linux下的函式執行時間的統計方法

2009 11 06 21 57 33 分類 預設分類 字型大小 訂閱 如何測試某個函式的執行時間是做實驗時經常用到的功能,在此比較linux下的測試函式,主要是其精確度。我們採用統一的測試標準程式 standard.c include define max 1000 the loop count ...

Linux下的函式執行時間的統計方法

如何測試某個函式的執行時間是做實驗時經常用到的功能,在此比較linux下的測試函式,主要是其精確度。我們採用統一的測試標準程式 standard.c include define max 1000 the loop count function do loop operation input nul...

Linux下的函式執行時間的統計方法

如何測試某個函式的執行時間是做實驗時經常用到的功能,在此比較linux下的測試函式,主要是其精確度。我們採用統一的測試標準程式 standard.c include define max 1000 the loop count function do loop operation input nul...