萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 微秒級精確時間測量:gettimeofday() 與 timeval 結構應用

Linux 系統下精確到微秒級的時間操作函數

秒級精度用 time() 即可;毫秒/微秒級需用 gettimeofday()。

核心函數:gettimeofday()

提供秒與微秒雙重精度,使用 struct timeval 結構:

struct timeval {
    long tv_sec;   // 秒
    long tv_usec;  // 微秒
};

實際應用範例:測量函數執行時間

#include 
#include 
#include 
#include 

void function() {
    unsigned int i, j;
    double y;
    for (i = 0; i < 10000; i++)
        for (j = 0; j < 10000; j++)
            y = sin((double)i);
}

int main(int argc, char **argv) {
    struct timeval tpstart, tpend;
    float timeuse;
    gettimeofday(&tpstart, NULL);
    function();
    gettimeofday(&tpend, NULL);
    timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
    timeuse /= 1000000;
    printf("Used Time: %f 秒\n", timeuse);
    exit(0);
}

記錄開始/結束時間,計算差值(微秒),轉換為秒,得精確執行時間。

總結

gettimeofday() 搭配 struct timeval 是 Linux 微秒級時間測量簡單有效方式,廣泛用於效能測試、延遲分析。

copyright © 萬盛學電腦網 all rights reserved