任一進程都可調用times函數以獲得它自己及已終止子進程的墻上時鐘時間、用戶CPU時間和系統CPU時間(關于這三種時間的含義可參考:http://www.CUOXin.com/nufangrensheng/p/3495526.html)。
#include <sys/times.h>clock_t times( struct tms *buf );返回值:若成功則返回流逝的墻上時鐘時間(單位:時鐘滴答數),若出錯則返回-1
此函數填寫由buf指向的tms結構,該結構定義如下:
struct tms { clock_t tms_utime; /* user CPU time */ clock_t tms_stime; /* system CPU time */ clock_t tms_cutime; /* user CPU time, terminated children */ clock_t tms_cstime; /* system CPU time, terminated children */};
注意,此結構沒有包含墻上時鐘時間的任何測量值。作為替代,times函數返回墻上時鐘時間作為其函數值。此值是相對于過去的某一時刻測量的,所以不能用其絕對值,而必須使用其相對值。例如,調用times,保存其返回值。在以后某個時間再次調用times,從新的返回值中減去以前的返回值,此差值就是墻上時鐘時間。
該結構中兩個針對子進程的字段包含了此進程用wait、waitpid或waitid已等待到的各個子進程的值。
所有由此函數返回的clock_t值都用_SC_CLK_TCK(由sysconf函數返回的每秒鐘滴答數)變換成秒數。
#include "apue.h"#include <sys/times.h>static void PR_times(clock_t, struct tms *, struct tms *);static void do_cmd(char *);int main(int argc, char *argv[]){ int i; setbuf(stdout, NULL); for(i=1; i<argc; i++) { do_cmd(argv[i]); /* once for each command-line arg */ } exit(0);}static voiddo_cmd(char *cmd) /* execute and time the "cmd" */{ struct tms tmsstart, tmsend; clock_t start, end; int status; printf("/ncommand: %s/n", cmd); if((start = times(&tmsstart)) == -1) /* starting values */ err_sys("times error"); if((status = system(cmd)) < 0) /* execute command */ err_sys("system error"); if((end = times(&tmsend)) == -1) /* ending values */ err_sys("times error"); pr_times(end-start, &tmsstart, &tmsend); pr_exit(status);}static voidpr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend){ static long clktck = 0; if(clktck ==0) /* fetch clock ticks per second first time */ if((clktck = sysconf(_SC_CLK_TCK)) < 0) err_sys("sysconf error"); printf(" real: %7.2f/n", real / (double)clktck); printf(" user: %7.2f/n", (tmsend->tms_utime - tmsstart->tms_utime) / (double)clktck); printf(" sys: %7.2f/n", (tmsend->tms_stime - tmsstart->tms_stime) / (double)clktck); printf(" child user: %7.2f/n", (tmsend->tms_cutime - tmsstart->tms_cutime) / (double)clktck); printf(" child sys: %7.2f/n", (tmsend->tms_cstime - tmsstart->tms_cstime) / (double)clktck);}
運行此程序得到:
本篇博文內容摘自《UNIX環境高級編程》(第二版),僅作個人學習記錄所用。關于本書可參考:http://www.apuebook.com/。
新聞熱點
疑難解答