times系统调用可以得到进程所消耗的时间,man 2times可以得到times系统调用的帮助。
#include <sys/times.h>
clock_t times(struct tms *buf);
struct tms {
clock_t tms_utime; /* usertime */
clock_t tms_stime; /* systemtime */
clock_t tms_cutime; /* user time of children*/
clock_t tms_cstime; /* system time of children*/
};
其中时间都是以时钟滴答数(clocktick)为单位,并不能保证非常精确。在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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。