代码之家  ›  专栏  ›  技术社区  ›  snakile

我如何用C来度量时间?

  •  37
  • snakile  · 技术社区  · 14 年前

    我想知道一些代码块执行了多长时间(大约)。像这样:

    startStopwatch();
    // do some calculations
    stopStopwatch();
    printf("%lf", timeMesuredInSeconds);
    

    怎么用?

    6 回复  |  直到 6 年前
        1
  •  59
  •   Joey Gumbo    14 年前

    你可以使用 clock 方法在 time.h

    例子:

    clock_t start = clock();
    /*Do something*/
    clock_t end = clock();
    float seconds = (float)(end - start) / CLOCKS_PER_SEC;
    
        2
  •  17
  •   Stephen    14 年前

    你可以使用 time.h 图书馆,特别是 time difftime 功能:

    /* difftime example */
    #include <stdio.h>
    #include <time.h>
    
    int main ()
    {
      time_t start,end;
      double dif;
    
      time (&start);
      // Do some calculation.
      time (&end);
      dif = difftime (end,start);
      printf ("Your calculations took %.2lf seconds to run.\n", dif );
    
      return 0;
    }
    

    (示例改编自上面链接的difftime网页。)

    请注意,这种方法只能提供秒的准确度- time_t 记录自 UNIX epoch (1970年1月1日)。

        3
  •  2
  •   selbie    14 年前

    GETICKCOUNT()。

    #include <windows.h>
    void MeasureIt()
    {
        DWORD dwStartTime = GetTickCount();
        DWORD dwElapsed;
    
        DoSomethingThatYouWantToTime();
    
        dwElapsed = GetTickCount() - dwStartTime;
    
        printf("It took %d.%3d seconds to complete\n", dwElapsed/1000, dwElapsed - dwElapsed/1000);
    }
    
        4
  •  1
  •   Andreas Rejbrand    14 年前

    我会用 QueryPerformanceCounter QueryPerformanceFrequency Windows API的函数。在块之前和之后调用前者,并减去(当前值-旧值)以获取实例之间的“滴答”数。除以后一个函数得到的值,得到以秒为单位的持续时间。

        5
  •  0
  •   user357501    14 年前

    如果不需要出色的分辨率,可以使用gettickCount(): http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx (如果它不是针对你自己的简单诊断,那么注意这个数字可以环绕,所以你需要用一点算术来处理它)。

    QueryPerformanceCounter是另一个合理的选项。(在msdn上也有描述)

        6
  •  0
  •   Ivan Talalaev    6 年前

    有时需要测量 天文时间 而不是 CPU时间 (尤其适用于 Linux ):

    #include <time.h>
    
    double what_time_is_it()
    {
        struct timespec now;
        clock_gettime(CLOCK_REALTIME, &now);
        return now.tv_sec + now.tv_nsec*1e-9;
    }
    
    int main() {
        double time = what_time_is_it();
        printf("time taken %.6lf\n", what_time_is_it() - time);
        return 0;
    }