指令列快速測量
$ time ./myprogram
real 0m2.033s # 真實牆鐘時間
user 0m2.032s # 用戶態 CPU 時間
sys 0m0.000s # 核心態 CPU 時間
程式碼內嵌測量(適用無法用 time 指令的場景)
#include <sys/times.h>
#include <stdio.h>
#include <string.h>
static struct tms tms_start, tms_end;
static clock_t c_start, c_end;
void timer_start()
{
memset(&tms_start, 0, sizeof(tms_start));
memset(&tms_end, 0, sizeof(tms_end));
c_start = times(&tms_start);
}
void timer_stop()
{
c_end = times(&tms_end);
printf("clock time: %ld, user/system cpu time: %ld/%ld\n",
c_end - c_start,
tms_end.tms_utime - tms_start.tms_utime,
tms_end.tms_stime - tms_start.tms_stime);
}
三種時間含義
| 時間類型 | 含義 | 單位 |
| Real (Wall-clock) | 從啟動到結束的實際經過時間,含 I/O 等待、其他進程搶佔 | 秒/毫秒 |
| User CPU | 進程在用戶態執行的 CPU 時間總和 | 時脈節拍 |
| System CPU | 進程在核心態(系統呼叫)執行的 CPU 時間總和 | 時脈節拍 |
關鍵函數說明
times(struct tms *buf):回傳開機至今的時脈數,並填入 tms_utime、tms_stime、tms_cutime、tms_cstime
sysconf(_SC_CLK_TCK):取得每秒時脈數(通常 100),將時脈換算為秒:秒 = 時脈 / CLK_TCK
clock():C 標準庫函數,回傳進程佔用的 CPU 時脈(user+sys),精度較低
完整可執行範例
#include <sys/times.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
struct tms t1, t2;
clock_t c1, c2;
long clk_tck = sysconf(_SC_CLK_TCK);
c1 = times(&t1);
// 模擬計算密集任務
double sum = 0;
for (long i = 0; i < 100000000; i++) sum += i * 0.1;
c2 = times(&t2);
printf("Real: %.3f s\n", (double)(c2 - c1) / clk_tck);
printf("User: %.3f s\n", (double)(t2.tms_utime - t1.tms_utime) / clk_tck);
printf("System: %.3f s\n", (double)(t2.tms_stime - t1.tms_stime) / clk_tck);
return 0;
}