分类:
2008-11-26 18:05:55
8.16 process times
讲了怎么给一个process计时,这个计时包括:
1. Clock time及程序总共从启动到结束的时间差
2. user time,即在用户层使用的时间
3. system time即,在system层使用的时间。
当然要求在启动时和退出时两个时间点作两次记录,然后两次的结果做减法来得到。
单位都是ticks,一般CPU在一秒钟都有几十个ticks,这个可以通过sysconf获得。
接口:
|
#include clock_t times(struct tms *buf); |
|
Returns: elapsed wall clock time in clock ticks if OK, 1 on error |
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 */ };
例子:
#include "apue.h"#include static void pr_times(clock_t, struct tms *, struct tms *);static void do_cmd(char *); intmain(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);}
结果:
$ ./a.out "sleep 5" "date" command: sleep 5 real: 5.02 user: 0.00 sys: 0.00 child user: 0.01 child sys: 0.00 normal termination, exit status = 0 command: date Mon Mar 22 00:43:58 EST 2004 real: 0.01 user: 0.00 sys: 0.00 child user: 0.01 child sys: 0.00 normal termination, exit status = 0