进程控制之进程时间

任一进程都可调用times函数以获得它自己及已终止子进程的墙上时钟时间、用户CPU时间和系统CPU时间(关于这三种时间的含义可参考:http://www.cnblogs.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 void
do_cmd(char *cmd)    /* execute and time the "cmd" */
{
    struct tms tmsstart, tmsend;
    clock_t    start, end;
    int     status;

    printf("
command: %s
", 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 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)
            err_sys("sysconf error");
    printf("  real:    %7.2f
", real / (double)clktck);
    printf("  user:    %7.2f
", 
        (tmsend->tms_utime - tmsstart->tms_utime) / (double)clktck);
    printf("  sys:    %7.2f
", 
        (tmsend->tms_stime - tmsstart->tms_stime) / (double)clktck);
    printf("  child user:    %7.2f
", 
        (tmsend->tms_cutime - tmsstart->tms_cutime) / (double)clktck);
    printf("  child sys:    %7.2f
", 
        (tmsend->tms_cstime - tmsstart->tms_cstime) / (double)clktck);
}

运行此程序得到:

未命名

本篇博文内容摘自《UNIX环境高级编程》(第二版),仅作个人学习记录所用。关于本书可参考:http://www.apuebook.com/

原文地址:https://www.cnblogs.com/nufangrensheng/p/3512749.html