8.15 进程时间
8.15 进程时间
在1 . 1 0节中说明了墙上时钟时间、用户CPU时间和系统CPU时间。任一进程都可调用times函数以获得它自己及终止子进程的上述值。
#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,从新返回的值中减去以前返回的值,此差值就是墙上时钟时间。
所有由此函数返回的clock_t值都用_SC_CLK_TCK (由sysconf函数返回的每秒时钟滴答数,见2.5.4节)变换成秒数。
实例
程序8 - 1 8将每个命令行参数作为shell命令串执行,对每个命令计时,并打印从tms结构取得的值。按下列方式运行此程序,得到:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.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 void do_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 */
printf("times error");
if ((status = system(cmd)) < 0) /* execute command */
printf("system() error");
if ((end = times(&tmsend)) == -1) /* ending values */
printf("times error");
pr_times(end - start, &tmsstart, &tmsend);
//pr_exit(status);
}
static void
pr_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)
printf("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.03
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.00
command: date
Wed Oct 24 03:57:00 PDT 2012
real: 0.09
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.08
在这个实例中,在child user和child sys行中显示的时间是执行shell和命令的子进程所使用的CPU时间。