linux下获取微秒级精度的时间

使用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
", start.tv_sec, start.tv_usec);
    sleep(1);
    gettimeofday( &end, NULL );
    printf("end   : %d.%d
", 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);// 百万分之一秒
原文地址:https://www.cnblogs.com/zhubaohua-bupt/p/7182821.html