文章出處
文章列表
1、前言
測試一個程序的執行時間,時間包括用戶CPU時間、系統CPU時間、時鐘時間。之前獲取之前時間都是在程序的main函數用time函數實現,這個只能粗略的計算程序的執行時間,不能準確的獲取其他時間。在看《APUE》時,書中有關程序時間測試程序,非常正規,提供這三個時間。如是,上網搜了一下,進行總結一下。
2、獲取方法
有兩種方法可以獲取,第一種是用time命令,time 進程。第二種是通過在程序中進行記錄,首先利用sysconf函數獲取時鐘滴答數,再用times獲取tms結構。
查看times函數,man 2 tms,得到tms結構定義和times函數聲明如下:
struct tms {
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children */
};
#include <sys/times.h> clock_t times(struct tms *buf);
注意:此處計算的時間是時鐘滴答數,需要除以系統時鐘滴答數,得出實際的秒數。
3、測試例子:
測試程序如下:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/times.h>
4 #include <unistd.h>
5
6 #define BUFFER_SIZE 4 * 1024
7
8 int main()
9 {
10 int sc_clk_tck;
11 sc_clk_tck = sysconf(_SC_CLK_TCK);
12
13 struct tms begin_tms, end_tms;
14 clock_t begin, end;
15 system("date");
16 begin = times(&begin_tms);
17 sleep(2);
18 end = times(&end_tms);
19
20 printf("real time: %lf\n", (end - begin) / (double)sc_clk_tck);
21 printf("user time: %lf\n",
22 (end_tms.tms_utime - begin_tms.tms_utime) / (double)sc_clk_tck);
23 printf("sys time: %lf\n",
24 (end_tms.tms_stime - begin_tms.tms_stime) / (double)sc_clk_tck);
25 printf("child user time: %lf\n",
26 (end_tms.tms_cutime - begin_tms.tms_cutime) / (double)sc_clk_tck);
27 printf("child sys time: %lf\n",
28 (end_tms.tms_cstime - begin_tms.tms_cstime) / (double)sc_clk_tck);
29 return 0;
30 }
測試結果如下所示:
采用time命令,測試結果如下所示:
4、參考網址
文章列表
全站熱搜