您的位置:首页 > 运维架构 > Linux

linux下C语言获取微秒级时间

2014-12-09 17:57 706 查看
使用C语言在linux环境下获得微秒级时间

1、数据结构

int gettimeofday(struct timeval*tv, struct timezone *tz);


其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:

struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}


timezone 参数若不使用则传入NULL即可。

而结构体timeval的定义为:

struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}


2、代码实例 temp.cpp

#include <stdio.h>        // for printf()
#include <sys/time.h>    // for gettimeofday()
#include <unistd.h>        // for sleep()

int main()
{
struct timeval start, end;
gettimeofday( &start, NULL );
printf("start : %d.%d\n", start.tv_sec, start.tv_usec);
sleep(1);
gettimeofday( &end, NULL );
printf("end   : %d.%d\n", end.tv_sec, end.tv_usec);

return 0;
}


3、编译

g++ -o temp temp.cpp


4、运行及结果

$ ./temp
start : 1418118324.633128
end   : 1418118325.634616


5、usleep函数

#include <unistd.h>

usleep(time);// 百万分之一秒


作者:风波

mail : fengbohello@qq.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: