进程时间
进程时间有墙上时钟时间、用户CPU时间和系统CPU时间。任一进程都可以调用 times 函数以获得它自己以及终止子进程的上述值。
/* 进程时间 */
/*
* 函数功能:获取进程的时间:墙上时钟时间、用户CPU时间和系统CPU时间;
* 返回值:若成功则返回流逝的墙上时钟时间(单位:时钟滴答数),若出错则返回-1;
* 函数原型:
*/
#include <sys/times.h>
clock_t times(struct tms *buf);
/*
* struct 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 */
};
在进程时间结构
tms 中并没有包含墙上时钟时间的测量值,
times 函数返回值可作为墙上时钟时间的测量值,其取值是两次
times 返回值的差值。由此函数返回的
clock_t 值都用
_SC_CLK_TCK(由
sysconf函数返回的每秒时钟滴答数)变换成秒数。
测试程序:
#include <sys/times.h>
#include <time.h>
#include "apue.h"
static void pr_times(clock_t, struct tms *, struct tms *);
static void do_cmd(char *);
void pr_exit(int status);
int main(int argc, char *argv[])
{
int i;
for(i=1; i<argc; i++){
do_cmd(argv[i]);
}
exit(0);
}
static void do_cmd(char* cmd)
{
struct tms tmsstart, tmsend;
clock_t start, end;
int status;
printf("\ncommand: %s\n", cmd);
if((start=times(&tmsstart)) == -1)
err_sys("times error");
if((status = system(cmd)) < 0)
err_sys("system error");
if((end = times(&tmsend)) == -1)
err_sys("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 = 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);
}
void pr_exit(int status)
{
if(WIFEXITED(status))
printf("normal termination, exit status = %d\n", WEXITSTATUS(status));
else if(WIFSIGNALED(status))
printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status),
#ifdef WCOREDUMP
WCOREDUMP(status) ? "(core file generated)" : " ");
#else
" ");
#endif
else if(WIFSTOPPED(status))
printf("child stoped, signal number = %d\n", WSTOPSIG(status));
}
输出结果:
执行:./time "date"
输出结果:
command: date
Fri Nov 7 20:31:13 CST 2014
real: 0.00
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.00
normal termination, exit status = 0
参考资料:
《unix高级环境编程》