獲取qemu系統當前時間(納秒級)並輸出到log的C實現

主要過程:
1.獲取納秒級系統時間
2.將該輸出重定向至log
主要函數:
1.clock_gettime
2.write_log
函數分析:
1.時間函數:
包含於頭文件stdio.h和time.h中;具體的實現有以下幾種
(1). Middleware對POSIX提供的標準計時器API進行封裝,主要提供了兩種類型的時鐘的封裝。一種是CLOCK_REALTIME,另一種是CLOCK_MONOTONIC。對與man手冊的解釋是:
CLOCK_REALTIME: Systemwide realtime clock. 系統範圍內的實時時鐘。用的是絕對時間,當系統時鐘源被改變,會受到影響
CLOCK_MONOTONIC:Represents monotonic time. Cannot be set.表示單調時間,不能被設置,它表示的是體統啓動至今的時間。
(2). 至於說爲何採用clock_gettime()函數,是因爲它提供精確到納秒級,qemu是採用納秒級的時間函數的。
2.輸出重定向
調用write_log(pFile, format, …);方法寫日誌;
會使用到va_list :va_list 是在C語言中解決變參問題的一組宏,所在頭文件:#include

#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <inttypes.h>

static inline uint64_t time_now(void)
{
    struct timespec time;
    clock_gettime(CLOCK_MONOTONIC, &time);
    return ((uint64_t) time.tv_sec) * 1000000000 + time.tv_nsec;
}

int write_log(FILE* pFile,const char *format,...)
{
    va_list arg;
    int done;

    va_start (arg,format);
    uint64_t time = time_now();
    fprintf(pFile,"%"PRIu64"\n",time);
    done = vfprintf(pFile,format,arg);
    va_end(arg);

    fflush(pFile);
    return done;
}
int main()
{
    FILE* pFile = fopen("time.txt","a");
    write_log(pFile,"%s\n","running!!!");
    fclose(pFile);
    return 0;
}

解析:
va_list (ap):定義va_list類型的變量ap
va_start(ap,v):初始化,將ap指針指向第一個可變參數的地址
va_arg(ap,t):獲取當前指針指向的資源,並將指針指向下一位
va_end:釋放va_list

編譯:
gcc time.c -o time
結果:
61575921805135
running!!!
參考鏈接:
http://blog.csdn.net/aihao1984/article/details/5953668
http://blog.csdn.net/subaofa/article/details/53609857

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章