linux下C語言獲取微秒級時間


使用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

 


免責聲明!

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



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