clock()、time()、clock_gettime()和gettimeofday()函数的用法和区别【转】
转自http://blog.sina.com.cn/s/blog_790f5ae10100rwd3.html
(一)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 <stdio.h>
#include <stdlib.h>
#include <time.h>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 test1time ./test1
Time to do 1000 empty loops is 0.180000 secondsreal 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 <sys/times.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>static void do_cmd(char *);
static void pr_times(clock_t, struct tms *, struct tms *);int main(int argc, char *argv[]){int i;for(i=1; argv[i]!=NULL; i++){do_cmd(argv[i]);}exit(1);
}
static void do_cmd(char *cmd){struct tms tmsstart, tmsend;clock_t start, end;int status;if((start=times(&tmsstart))== -1)puts("times error");if((status=system(cmd))<0)puts("system error");if((end=times(&tmsend))== -1)puts("times error");pr_times(end-start, &tmsstart, &tmsend);exit(0);
}
static void pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend){static long clktck=0;if(0 == clktck)if((clktck=sysconf(_SC_CLK_TCK))<0)puts("sysconf err");printf("real:%7.2f\n", real/(double)clktck);printf("user-cpu:%7.2f\n", (tmsend->tms_utime - tmsstart->tms_utime)/(double)clktck);printf("system-cpu:%7.2f\n", (tmsend->tms_stime - tmsstart->tms_stime)/(double)clktck);printf("child-user-cpu:%7.2f\n", (tmsend->tms_cutime - tmsstart->tms_cutime)/(double)clktck);printf("child-system-cpu:%7.2f\n", (tmsend->tms_cstime - tmsstart->tms_cstime)/(double)clktck);
}编译:
gcc test2.c -o test2测试这个程序:
time ./test2 "dd if=/dev/zero f=/dev/null bs=1M count=10000"
10000+0 records in
10000+0 records out
10485760000 bytes (10 GB) copied, 4.93028 s, 2.1 GB/s
real: 4.94
user-cpu: 0.00
system-cpu: 0.00
child-user-cpu: 0.01
child-system-cpu: 4.82real 0m4.943s
user 0m0.016s
sys 0m4.828s
3)总结:
(1)通过这个测试,系统的time程序与test2程序输出基本一致了.
(2)(double)clktck是通过clktck=sysconf(_SC_CLK_TCK)来取的,也就是要得到user-cpu所占用的时间,就要用
(tmsend->tms_utime - tmsstart->tms_utime)/(double)clktck);
(3)clock_t times(struct tms *buf);返回值是过去一段时间内时钟嘀嗒的次数.
(4)times()函数返回值也是一个相对时间.
(三)实时函数clock_gettime
在POSIX1003.1中增添了这个函数,它的原型如下:
int clock_gettime(clockid_t clk_id, struct timespec *tp);
它有以下的特点:
1)它也有一个时间结构体:timespec ,timespec计算时间次数的单位是十亿分之一秒.
strace timespec{time_t tv_sec;long tv_nsec;
}
2)clockid_t是确定哪个时钟类型.
CLOCK_REALTIME: 标准POSIX实时时钟
CLOCK_MONOTONIC: POSIX时钟,以恒定速率运行;不会复位和调整,它的取值和CLOCK_REALTIME是一样的.
CLOCK_PROCESS_CPUTIME_ID和CLOCK_THREAD_CPUTIME_ID是CPU中的硬件计时器中实现的.
3)测试:
#include<time.h>
#include<stdio.h>
#include<stdlib.h>#define MILLION 1000000
int main(void)
{long int loop = 1000;struct timespec tpstart;struct timespec tpend;long timedif;clock_gettime(CLOCK_MONOTONIC, &tpstart);while (--loop){system("cd");}clock_gettime(CLOCK_MONOTONIC, &tpend);timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;fprintf(stdout, "it took %ld microseconds\n", timedif);return 0;
}编译:
gcc test3.c -lrt -o test3计算时间:
time ./test3
it took 3463843 microsecondsreal 0m3.467s
user 0m0.512s
sys 0m2.936s
(四)时间函数gettimeofday()
1)概述:
gettimeofday()可以获得当前系统的时间,是一个绝对值
原型如下:
int gettimeofday ( struct timeval * tv , struct timezone * tz )
timeval结型体的原型如下:
struct timeval {time_t tv_sec; suseconds_t tv_usec; };
所以它可以精确到微秒
测试:
#include <stdio.h>
#include <unistd.h>
int
main(){int i=10000000;struct timeval tvs,tve;gettimeofday(&tvs,NULL);while (--i);gettimeofday(&tve,NULL);double span = tve.tv_sec-tvs.tv_sec + (tve.tv_usec-tvs.tv_usec)/1000000.0;printf("time: %.12f\n",span);return 0;
}gcc test5.c
./a.out
time: 0.041239000000
(五)四种时间函数的比较
1)精确度比较:
以下是各种精确度的类型转换:
1秒=1000毫秒(ms), 1毫秒=1/1000秒(s);
1秒=1000000 微秒(μs), 1微秒=1/1000000秒(s);
1秒=1000000000 纳秒(ns),1纳秒=1/1000000000秒(s);
clock()函数的精确度是10毫秒(ms)
times()函数的精确度是10毫秒(ms)
gettimofday()函数的精确度是微秒(μs)
clock_gettime()函数的计量单位为十亿分之一,也就是纳秒(ns)
3)测试4种函数的精确度:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#include <sys/time.h>
#define WAIT for(i=0;i<298765432;i++);
#define MILLION 1000000int
main ( int argc, char *argv[] )
{int i;long ttt;clock_t s,e;struct tms aaa;s=clock();WAIT;e=clock();printf("clock time : %.12f\n",(e-s)/(double)CLOCKS_PER_SEC);long tps = sysconf(_SC_CLK_TCK);s=times(&aaa);WAIT;e=times(&aaa);printf("times time : %.12f\n",(e-s)/(double)tps);struct timeval tvs,tve;gettimeofday(&tvs,NULL);WAIT;gettimeofday(&tve,NULL);double span = tve.tv_sec-tvs.tv_sec + (tve.tv_usec-tvs.tv_usec)/1000000.0;printf("gettimeofday time: %.12f\n",span);struct timespec tpstart;struct timespec tpend;clock_gettime(CLOCK_REALTIME, &tpstart);WAIT;clock_gettime(CLOCK_REALTIME, &tpend);double timedif = (tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000000000.0;printf("clock_gettime time: %.12f\n", timedif);return EXIT_SUCCESS;
}gcc -lrt test4.c -o test4
debian:/tmp# ./test4
clock time : 1.190000000000
times time : 1.180000000000
gettimeofday time: 1.186477000000
clock_gettime time: 1.179271718000
(六)内核时钟
默认的Linux时钟周期是100HZ,而现在最新的内核时钟周期默认为250HZ.
如何得到内核的时钟周期呢?
grep ^CONFIG_HZ /boot/config-2.6.26-1-xen-amd64
CONFIG_HZ_250=y
CONFIG_HZ=250
结果就是250HZ.
而用sysconf(_SC_CLK_TCK);得到的却是100HZ
例如:
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#include <sys/time.h>int main ( int argc, char *argv[] )
{long tps = sysconf(_SC_CLK_TCK);printf("%ld\n", tps);return EXIT_SUCCESS;
}
为什么得到的是不同的值呢?
因为sysconf(_SC_CLK_TCK)和CONFIG_HZ所代表的意义是不同的.
sysconf(_SC_CLK_TCK)是GNU标准库的clock_t频率.
它的定义位置在:/usr/include/asm/param.h
例如:
#ifndef HZ
#define HZ 100
#endif
最后总结一下内核时间:
内核的标准时间是jiffy,一个jiffy就是一个内部时钟周期,而内部时钟周期是由250HZ的频率所产生中的,也就是一个时钟滴答,间隔时间是4毫秒(ms).
也就是说:
1个jiffy=1个内部时钟周期=250HZ=1个时钟滴答=4毫秒
每经过一个时钟滴答就会调用一次时钟中断处理程序,处理程序用jiffy来累计时钟滴答数,每发生一次时钟中断就增1.
而每个中断之后,系统通过调度程序跟据时间片选择是否要进程继续运行,或让进程进入就绪状态.
最后需要说明的是每个操作系统的时钟滴答频率都是不一样的,LINUX可以选择(100,250,1000)HZ,而DOS的频率是55HZ.
(七)为应用程序计时
用time程序可以监视任何命令或脚本占用CPU的情况.
1)bash内置命令time
例如:
time sleep 1
real 0m1.016s
user 0m0.000s
sys 0m0.004s
2)/usr/bin/time的一般命令行
例如:
\time sleep 1
0.00user 0.00system 0:01.01elapsed 0%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (1major+176minor)pagefaults 0swaps
注:
在命令前加上斜杠可以绕过内部命令.
/usr/bin/time还可以加上-v看到更具体的输出:
\time -v sleep 1Command being timed: "sleep 1"User time (seconds): 0.00System time (seconds): 0.00Percent of CPU this job got: 0%Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.00Average shared text size (kbytes): 0Average unshared data size (kbytes): 0Average stack size (kbytes): 0Average total size (kbytes): 0Maximum resident set size (kbytes): 0Average resident set size (kbytes): 0Major (requiring I/O) page faults: 0Minor (reclaiming a frame) page faults: 178Voluntary context switches: 2Involuntary context switches: 0Swaps: 0File system inputs: 0File system outputs: 0Socket messages sent: 0Socket messages received: 0Signals delivered: 0Page size (bytes): 4096Exit status: 0
这里的输出更多来源于结构体rusage.
最后,我们看到real time大于user time和sys time的总和,这说明进程不是在系统调用中阻塞,就是得不到运行的机会.
而sleep()的运用,也说明了这一点.
clock()、time()、clock_gettime()和gettimeofday()函数的用法和区别【转】相关推荐
- clock()、time()、clock_gettime()和gettimeofday()函数的用法和区别
转自http://blog.sina.com.cn/s/blog_790f5ae10100rwd3.html 一)ANSI clock函数 1)概述: clock 函数的返回值类型是clock_t,它 ...
- exec函数组六个函数的用法和区别
exec函数组有六个函数,分别是: #include <unistd.h> extern char **environ; int execl(const char *path, const ...
- Kotlin 标准库中run、let、also、apply、with函数的用法和区别
run 函数 定义: inline fun <R> run(block: () -> R): R //1 Calls the specified function block and ...
- Freemarker宏和函数的用法和区别
1.宏(macro) 写法: <#macro page url page maskSize=5> <#if (number == pages)> <li>& ...
- SQL 中round(),floor(),ceiling()函数的用法和区别
round() 遵循四舍五入把原值转化为指定小数位数 floor()向下舍入为指定小数位数 如:floor(1.45)= 1;floor(1.55) = 1 ceiling()向上舍入为指定小数位数 ...
- torch.bmm()和torch.matmul()函数的用法和区别,矩阵相乘
torch.bmm()和torch.matmul()都是矩阵乘法的运算函数,区别是,torch.matmul更强大. 两者都可以支持3维的矩阵运算,实际是第一维只是找下标,后面2维才是矩阵,然后对应做 ...
- map函数、filer函数、reduce函数的用法和区别
Map函数 map函数的用法如下: def add_one(x):return x+1#使用普通函数 v1 = map(add_one,[1,2,3]) v1 = list(v1) print(v1) ...
- rand函数和srand函数的用法和区别
srand初始化随机种子,rand产生随机数 rand(产生随机数) 表头文件: #include<stdlib.h> //标准库 <cstdlib> (被 ...
- MYSQL 中round(),floor(),ceiling()函数的用法和区别?
//应用中使用四舍五入的值,我和我的用户在报表应用中的计算问题存在分歧.所有的代码都在T-SQL中,但是我认为报表问题与数据类型和向下取整或向上取整规则关系密切.请问您有没有这方面的高见?我想看到一些 ...
- SQL 中详解round(),floor(),ceiling()函数的用法和区别?
应用中使用四舍五入的值,我和我的用户在报表应用中的计算问题存在分歧.所有的代码都在T-SQL中,但是我认为报表问题与数据类型和向下取整或向上取整规则关系密切.请问您有没有这方面的高见?我想看到一些带有 ...
最新文章
- 2018-3-7 HDFS架构
- 【好书试读】支付宝体验设计精髓
- 对移动APP开发的需求分析的观点及见解
- Centos7 安装mongodb记录
- ajax: jquery get request
- Taro+react开发(32)注意符号
- 一篇文章搞懂数据仓库:数据仓库架构-Lambda和Kappa对比
- 44年前的一个数学猜想终被破解
- 为什么 mysql 里的 ibdata1 文件不断的增长?
- C++面试题-面向对象-多态性与虚函数
- 你说你会用Companion object?恐怕不是!
- GSEA分析详细步骤
- css空心半圆的实现,css – 透明空心或切出圆
- 软件项目开发流程逻辑图
- location.hostnbsp;与nbsp;locat…
- 彻底了解DVD:从入门到精通
- java开发基础(面试必备)
- android studio怎么后退,Android Studio:上一个活动的后退按钮
- Android 使用 7z 压缩字符串(工作总结)
- IAR 修改工程名称
热门文章
- android系统与苹果手机号码,苹果手机号码怎么导入另一个手机安卓(全程图解其操作流程)...
- 【饭谈】职业生涯的关键:不破不立
- [博创智联]创新创客智能硬件平台——三轴加速度传感器
- Error: The project seems to require yarn but it‘s not installed.
- 制作FlappyBird时出现的一些问题
- android allow usb debugging,Android USB debugging 功能失效
- java如何表格一样对齐_如何水平对齐表格? (How can I horizontally align a form?)
- IP地址中的网络地址和主机地址分别是什么意思
- codeforces949D Curfew
- HaaS EDU K1 快速搭建Python开发环境