測試程序運行時間

1. 使用 clock() 測試運行時間

#include <time.h>

int main(int argc, char *argv[])
{
    clock_t start = clock();

    /* your code here... */

    clock_t end = clock();
    double timeuse = (double)(end - start) / CLOCKS_PER_SEC;
    return 0;
}

此方案代碼編寫較容易,清晰明瞭,缺點:精度較差

2. 使用 gettimeofday() 測試運行時間

#include <stdlib.h>
#include <sys/time.h>

int main(int argc, char *argv[])
{
    struct timeval start;
    struct timeval end;
    double elapsed = 0;

    gettimeofday(&start, NULL);

    /* your code here... */

    gettimeofday(&end, NULL);

    elapsed = (end.tv_sec - start.tv_sec) * 1000000
        + (end.tv_usec - start.tv_usec);
    elapsed /= 1000000;
    return 0;
}

使用<sys/time.h>裏面的 gettimeofday 函數計算,精度達到微秒級,比 clock() 要精確得多。
struct timeval 定義於 <bits/time.h> 頭文件:

struct timeval
  {
    __time_t tv_sec;        /* Seconds.  */
    __suseconds_t tv_usec;  /* Microseconds.  */
  };
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章