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\n", start.tv_sec, start.tv_usec);
  10.  
    sleep( 1);
  11.  
    gettimeofday( &end, NULL );
  12.  
    printf( "end : %d.%d\n", 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM