10.07 进程时间 tms

什么是进程时间

进程时间包含:

  1. CPU 在用户模式下消耗的时间。
  2. CPU 在内核模式下消耗的时间(比如 I/O、页错误处理)。

times 系统调用

#include <sys/times.h>

clock_t times(struct tms *buf);

其中 tms 结构体包含了当前进程和等待的子进程的时间信息。“等待的子进程”含义是:只有调用 wait 或者 waitpid 回收了一个子进程,子进程的时间才会累加到当前进程的 tms_cutimetms_cstime 上。

struct tms {
   clock_t tms_utime;  /* user time */
   clock_t tms_stime;  /* system time */
   clock_t tms_cutime; /* user time of children */
   clock_t tms_cstime; /* system time of children */
};

返回值表示从一个任意时开始的时钟滴答数,因此只有两次返回值的差是有意义的。任意时和系统实现有关系,而且也有溢出的可能性,所以 man page 中推荐使用 clock_gettime(2) 来衡量时间。

times 函数所使用的 clock_t 频率由 sysconf(_SC_CLK_TCK) 决定,其数值除以这个值就得到了秒数。

在大多数 Linux 的硬件架构,sysconf(_SC_CLK_TCK)返回 100。与此对应的内核常量是 USER_HZ。然而 USER_HZ 在其他几个架构下可以被定义超过 100,如 Alpha 和 IA - 64。

标准库函数 clock

#include <time.h>

clock_t clock(void);

clock 函数返回进程在用户和内核模式下运行的粗略总时间。

在 POSIX.1,CLOCKS_PER_SEC 是常量 10000,但是不知道其类型(因此打印时最好先转换成更大的类型)。在我的计算机上,这个宏被定义为 ((__clock_t) 1000000)clock 返回值除以这个值就得到了秒数。

Note

虽然 times 函数和 clock 函数返回类型都是 clock_t,但是因为 POSIX 标准和 C 语言标准的不同,两者单位不同。