2009-07-03 19:48 在linux中如何获得微秒精度的时间?-转
2016-01-16 11:53
671 查看
※使用C的<time.h>库函数是无法达到微秒级别的时间的,所以上网找了一下答案,原文如下:
------------------------
使用C语言进行计时,在用户空间中可以使用C语言函数gettimeofday 得到时间,它的调用格式是:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);
结构timeval的定义为:
struct timeval {long tv_sec; /* 秒数 */long tv_usec; /* 微秒数 */};
可以看出,使用这种方式计时,[b]精度可达微秒,[/b]也就是10-6秒。进行计时的时候,我们需要前后调用两次gettimeofday,然后计算中间的差值:
gettimeofday( &start, NULL );
foo();
gettimeofday( &end, NULL );
timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
timeuse /= 1000000;
================================================================
补充:刚从我又查了一下C库函数手册。
Syntax:
#include <ctime> clock_t clock( void );
The clock() function returns the processor time since the program started, or - 1 if that information is unavailable. To convert the return value to seconds, divide it by CLOCKS_PER_SEC. (Note: if your compiler is POSIX compliant, then CLOCKS_PER_SEC
is always defined as 1000000.)
可见在符合POSIX标准的C编译器上,借助clock()函数也是可以获得微秒精度的时间值,但由于这样的代码依赖于编译器,所以不推荐使用。
------------------------
使用C语言进行计时,在用户空间中可以使用C语言函数gettimeofday 得到时间,它的调用格式是:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);
结构timeval的定义为:
struct timeval {long tv_sec; /* 秒数 */long tv_usec; /* 微秒数 */};
可以看出,使用这种方式计时,[b]精度可达微秒,[/b]也就是10-6秒。进行计时的时候,我们需要前后调用两次gettimeofday,然后计算中间的差值:
gettimeofday( &start, NULL );
foo();
gettimeofday( &end, NULL );
timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec - start.tv_usec;
timeuse /= 1000000;
================================================================
补充:刚从我又查了一下C库函数手册。
Syntax:
#include <ctime> clock_t clock( void );
The clock() function returns the processor time since the program started, or - 1 if that information is unavailable. To convert the return value to seconds, divide it by CLOCKS_PER_SEC. (Note: if your compiler is POSIX compliant, then CLOCKS_PER_SEC
is always defined as 1000000.)
可见在符合POSIX标准的C编译器上,借助clock()函数也是可以获得微秒精度的时间值,但由于这样的代码依赖于编译器,所以不推荐使用。
相关文章推荐
- arm-linux-gcc: No such file or directory
- linux 编码转换-转
- 使用iconv命令轻松实现linux下字符集编码的转换-转
- Linux学习笔记:Mysql的启动与关闭脚本
- Linux上VNC 启动和关闭 已经常见问题
- CPU与内存的那些事
- 学习linux/unix编程方法的建议-转
- 学习linux/unix编程方法的建议-转
- Linux文件及文件内容的查找-转
- linux 文件编码格式转换-转
- udp linux 获取本机ip
- 初窥Linux系统中的进程管理工具SystemD
- 远程登录管理工具SecureCRT连接VMWare下的CentOS
- linu计划任务学习
- CentOS7安装ZooKeeper(ZooKeeper3.3)
- Linux Socket 基础实例 (C语言版)-转
- Linux串口编程-转
- LINUX警告:检测到时钟错误。您的创建可能是不完整的。-转
- Linux段错误-转
- Linux调试工具strace和gdb常用命令小结-转