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

转自:https://blog.csdn.net/u011857683/article/details/81320052

使用C语言在linux环境下获得微秒级时间

1. 数据结构

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

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

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

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

而结构体timeval的定义为:

  1.  
    struct timeval{
  2.  
    long int tv_sec; // 秒数
  3.  
    long int tv_usec; // 微秒数
  4.  
    }

2. 代码实例 temp.cpp

  1.  
    #include <stdio.h> // for printf()
  2.  
    #include <sys/time.h> // for gettimeofday()
  3.  
    #include <unistd.h> // for sleep()
  4.  
     
  5.  
    int main()
  6.  
    {
  7.  
    struct timeval start, end;
  8.  
    gettimeofday( &start, NULL );
  9.  
    printf("start : %d.%d ", start.tv_sec, start.tv_usec);
  10.  
    sleep(1);
  11.  
    gettimeofday( &end, NULL );
  12.  
    printf("end : %d.%d ", end.tv_sec, end.tv_usec);
  13.  
     
  14.  
    return 0;
  15.  
    }

3. 运行结果

  1.  
    $ ./temp
  2.  
    start : 1418118324.633128
  3.  
    end : 1418118325.634616

4. usleep函数

  1.  
    #include <unistd.h>
  2.  
    usleep(time);// 百万分之一秒

本文转自:

https://blog.csdn.net/zhubaohua_bupt/article/details/52873082

原文地址:https://www.cnblogs.com/sky-heaven/p/10006086.html