times系统调用的例子

引用
#include <sys/times.h>
clock_t times (struct tms * buf );

函数功能 :
times系统调用可以得到进程所消耗的时间,man 2 times可以得到times系统调用的帮助。

说明 :
times() 函数返回从过去一个任意的时间点所经过的时钟数。返回值可能会超出 clock_t  (一般为 long 型) 的范围(溢出)。如果发生错误,则返回 (clock_t ) -1 类型,然后设置相应的 errno 值。

#include <sys/times.h>

clock_t times(struct tms *buf);

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 */
};

其中时间都是以时钟滴答数(clock tick)为单位,并不能保证非常精确。在2.6内核,1秒钟是100次。


例子:

#include <sys/times.h>
#include <unistd.h>
#include <stdio.h>

int main() {
struct tms buf;
int i;
clock_t c1, c2;
FILE* fp;
long CLK_TCK;

c1 = times(&buf);
// 这段代码用来消耗时间
for(i=0;i<1000000;i++) {
fp = fopen("/tmp/1.tmp", "rb+");
fclose(fp);
}
c2 = times(&buf);
if(c2 == -1) {
perror("Failed");
}

printf("clock used = %d\n", c2 - c1);
printf("tms_utime = %d\n", buf.tms_utime);
printf("tms_stime = %d\n", buf.tms_stime);
printf("tms_cutime = %d\n", buf.tms_cutime);
printf("tms_cstime = %d\n", buf.tms_cstime);

CLK_TCK = sysconf(_SC_CLK_TCK);
printf("CLK_TCK = %d\n", CLK_TCK);
}

显示结果:

clock used = 354
tms_utime = 79
tms_stime = 274
tms_cutime = 0
tms_cstime = 0
CLK_TCK = 100

你可能感兴趣的:(times系统调用的例子)