天天看點

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

linux下擷取微秒級精度的時間
#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;
}      
linux下擷取微秒級精度的時間

3、編譯

g++ -o temp temp.cpp      

4、運作及結果

$ ./temp 
start : 1418118324.633128
end   : 1418118325.634616      

5、usleep函數

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