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

时间:2023-03-08 23:35:14
linux下获取微秒级精度的时间【转】

转自:https://blog.****.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. int main()
  5. {
  6. struct timeval start, end;
  7. gettimeofday( &start, NULL );
  8. printf("start : %d.%d\n", start.tv_sec, start.tv_usec);
  9. sleep(1);
  10. gettimeofday( &end, NULL );
  11. printf("end : %d.%d\n", end.tv_sec, end.tv_usec);
  12. return 0;
  13. }

3. 运行结果

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

4. usleep函数

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

本文转自:

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