我们可以测量进程的三种时间:墙上时钟时间,用户CPU时间和系统CPU时间。任一进程都可以调用times函数以获得它自己
以及终止子进程的上述值。
#include <sys/times.h> clock_t times(struct tms* buf); //若成功则返回流逝的墙上时钟时间(单位:时钟滴答数),若出错则返回-1.函数中buf的结构如下:
struct tms{ clock_t tms_utimes; //user cpu time clock_t tms_stimes; //system cpu time clock_t tms_cutime; //user cpu time, terminated children clock_t tms_cstime; //system cpu time, terminated children }要获取运行时间,必须获取相对值。例如,调用times,保存返回值,在以后某个时间再次调用times,从新的返回值中减去
以前的返回值,此差值就是墙上时钟时间。
所有由此函数返回的clock_t值都用_SC_CLK_TCK(由sysconf函数返回的每秒时钟滴答数)变换成秒数。
#include <stdio.h> #include <sys/times.h> #include <time.h> #include <unistd.h> static void pr_times(clock_t,struct tms*,struct tms*); static void do_cmd(char *); int main(int argc, char *argv[]){ int i; for(i=1; i<argc; i++){ do_cmd(argv[i]); } return 0; } static void do_cmd(char* cmd){ struct tms tmsstart, tmsend; clock_t start, end; int status; printf("command:%s\n",cmd); if((start=times(&tmsstart)) == -1){ perror("times"); return; } if((status = system(cmd))<0){ perror("system"); return; } if((end = times(&tmsend)) == -1){ perror("times"); return; } pr_times(end-start, &tmsstart, &tmsend); } static void pr_times(clock_t real, struct tms* tmsstart, struct tms* tmsend){ static long clktck = 0; if((clktck = sysconf(_SC_CLK_TCK))<0){ perror("sysconf"); return; } 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); }运行结果:
yan@yan-vm:~/apue$ ./a.out "dd if=/dev/zero of=/dev/null bs=1M count=1000"
command:dd if=/dev/zero of=/dev/null bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB) copied, 0.212456 s, 4.9 GB/s
real: 0.22
user: 0.00
sys: 0.00
child user: 0.01
child sys: 0.20