linux 内核 时间函数吗,Linux下时间度量的深入分析

一)ANSI clock函数

1)概述:

clock 函数的返回值类型是clock_t,它除以CLOCKS_PER_SEC来得出时间,一般用两次clock函数来计算进程自身运行的时间.

ANSI clock有三个问题:

1)如果超过一个小时,将要导致溢出.

2)函数clock没有考虑CPU被子进程使用的情况.

3)也不能区分用户空间和内核空间.

所以clock函数在linux系统上变得没有意义.

2)测试

编写test1.c程序,测试采用clock函数的输出与time程序的区别.

vi test1.c

#include

#include

#include

int main( void )

{

long i=1000L;

clock_t start, finish;

double  duration;

printf( "Time to do %ld empty loops is ", i );

start = clock();

while (--i){

system("cd");

}

finish = clock();

duration = (double)(finish - start) / CLOCKS_PER_SEC;

printf( "%f seconds\n", duration );

return 0;

}

gcc test1.c -o test1

time ./test1

Time to do 1000 empty loops is 0.180000 seconds

real    0m3.492s

user    0m0.512s

sys     0m2.972s

3)总结:

(1)程序调用 system("cd");,这里主要是系统模式子进程的消耗,test1程序不能体现这一点.

(2)0.180000 seconds秒的消耗是两次clock()函数调用除以CLOCKS_PER_SEC.

(3)clock()函数返回值是一个相对时间,而不是绝对时间.

(4)CLOCKS_PER_SEC是系统定义的宏,由GNU标准库定义为1000000.

二)times()时间函数

1)概述:

原型如下:

clock_t times(struct tms *buf);

tms结构体如下:

strace tms{

clock_t tms_utime;

clock_t tms_stime;

clock_t tms_cutime;

clock_t tms_cstime;

}

注释:

tms_utime记录的是进程执行用户代码的时间.

tms_stime记录的是进程执行内核代码的时间.

tms_cutime记录的是子进程执行用户代码的时间.

tms_cstime记录的是子进程执行内核代码的时间.

2)测试:

vi test2.c

#include

#include

#include

#include

#include

static void do_cmd(char *);

st

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值