如何得知某段代碼的運行時間

    轉自:http://blog.chinaunix.net/uid-27034868-id-3371737.html     
    之前,我的同學問了我一個算法題,由於這個題是要通過提交代碼然後在線測試的,有運行時間的限制。我想應該有辦法把某段代碼的運行時間計算出來,當然現在某些IDE(集成開發環境)已經提供了這個功能,但是我猜它只是計算進程開始至結束的時間,如果我們需要更精確,精確到某段代碼的運行時間的話,我們可以在代碼中加入相應的代碼就可以得到這個運行時間了。很多時候可以用於比較兩(幾)個算法的效率。
 
   下面給出兩個比較方便的方法在C語言中的使用(C++的更多本文不討論)

點擊(此處)摺疊或打開

  1. // count_time.c

  2. // 求2000000內素數和,並計算所用時間(精確)
  3. #include <stdio.h>
  4. #include <math.h>
  5. #include <sys/time.h> // struct timeval 的定義
  6. #include <time.h> // clock的定義

  7. void prime_number()
  8. {
  9.     unsigned long m, k, i;//, n = 0;
  10.     unsigned long sum = 0;

  11.     printf("2000000內素數和爲:\n");
  12.     for (= 3; m < 2000000;+= 2) {
  13.         k = (unsigned long)sqrt(m);
  14.         for (= 2; i <= k; i++) {
  15.             if (% i == 0)
  16.                 break;
  17.         }
  18.         if (>= k + 1)
  19.             sum += m;
  20.     }
  21.     printf("sum= %lld\n",sum+2);
  22. }

  23. // 計時方法一( 在Unix/Linux下使用)
  24. void count_runtime1()
  25. {
  26.     struct timeval start, end;

  27.     gettimeofday( &start, NULL );//第二個參數不爲空則用於返回時區結果,這裏不需要

  28.     //* 在start與end之間運行需要計時的代碼 
  29.     prime_number();
  30.     
  31.     gettimeofday( &end, NULL );
  32.     
  33.     unsigned int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + \
  34.                 end.tv_usec -start.tv_usec;
  35.                          
  36.     printf("timeuse: %d us(微妙)\n", timeuse);
  37. }

  38. // 計時方法2
  39. void count_runtime2()
  40. {
  41.     
  42.     /* 使用下面的clock獲取,更接近cpu運行時間 ,標準C更通用*/
  43.     clock_t clock_start = clock();
  44.     
  45.     prime_number();// 需要計時的代碼
  46.     
  47.     clock_t clock_end = clock();
  48.     
  49.     printf("timesue: %ld us\n", clock_end - clock_start);
  50. }

  51. int main()
  52. {
  53.     count_runtime1();
  54.     count_runtime2();
  55.     
  56.     return 0;
  57. }
  58. /******************************************************************************/
  59. /* man 手冊中對gettimeofday函數的說明:
  60. NAME
  61.        gettimeofday, settimeofday - get / set time

  62. SYNOPSIS
  63.        #include <sys/time.h>

  64.        int gettimeofday(struct timeval *tv, struct timezone *tz);
  65.        int settimeofday(const struct timeval *tv, const struct timezone *tz);

  66.    Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

  67.        settimeofday(): _BSD_SOURCE

  68. DESCRIPTION
  69.        The functions gettimeofday() and settimeofday() can get and set      the time as well as a timezone. The tv argument is a struct          meval (as specified in <sys/time.h>):

  70.            struct timeval {
  71.                time_t tv_sec; // seconds 
  72.                suseconds_t tv_usec; // microseconds 
  73.            };
  74.   …………
  75.   RETURN VALUE
  76.        gettimeofday() and settimeofday() return 0 for success, or -for fail?br />
  77.        ure (in which case errno is set appropriately).

  78. ***************************************************************************************/

  79. /* man 手冊中對clock函數的說明:
  80. NAME
  81.        clock - Determine processor time

  82. SYNOPSIS
  83.        #include <time.h>

  84.        clock_t clock(void);

  85. DESCRIPTION
  86.        The clock() function returns an approximation of processor time      used by the program.

  87. RETURN VALUE
  88.        The value returned is the CPU time used so far as a clock_t; to get      the number of seconds used, divide by CLOCKS_PER_SEC. If the      processor time used is not available or its value cannot be      represented, the
  89.        function returns the value (clock_t) -1.

  90. CONFORMING TO
  91.        C89, C99, POSIX.1-2001. POSIX requires that CLOCKS_PER_SEC equals
  92.        1000000 independent of the actual resolution.
  93.        int /usr/include/time.h #define CLOCKS_PER_SEC 1000000l

  94. NOTES
  95.        The C standard allows for arbitrary values at the start of the program;subtract the value returned from a call to clock() at the      start of the program to get maximum portability.
  96. ……
  97. ******************************************************************************/

發佈了15 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章