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

计算大型c++程序的运行时间

  •  2
  • AnkurVj  · 技术社区  · 14 年前

    建议的估计时间的方法是使用clock()函数,然后将cpu周期数除以cycles/second。

    我的问题是我试图运行的程序需要很多时间(以小时为单位)。这意味着clock()函数(返回long int)返回一个垃圾值(因为max long int不够大)

    有什么建议吗(除了估计内部循环的时间和把它们加起来之类的)?

    long t1 = clock();
    function();
    long t2=clock();
    
    time = ((double)t2 - t1) / CLOCKS_PER_SEC
    
    7 回复  |  直到 14 年前
        1
  •  1
  •   James McNellis    14 年前

    如果程序长时间运行,那么亚秒精度可能不是特别重要。既然如此,为什么不直接打电话 time() ?

        2
  •  5
  •   Justin Ethier    14 年前

    如果您在Linux/Unix下运行它,您可以说:

    time my_process
    
        3
  •  3
  •   abelenky    14 年前

    用百分比误差来考虑这个问题。

    如果你的程序需要几个小时运行(假设4小时。。。或14400秒),则1/2%的误差为72秒,或略大于1分钟。

    换言之,要想得到1/2%以内的准确答案,只需要精确到最接近的一分钟。假设一个手持式秒表可以计时到一秒钟内,甚至是十分之一秒,那么你的误差将是微不足道的。

    我的观点是,你可以用秒表或手持式秒表精确测量你的程序。

        4
  •  0
  •   osgx    14 年前

    gettimeofday()

    #include <sys/time.h>
    
    int gettimeofday(struct timeval *tv, NULL);
    

    函数gettimeofday()和settimeofday()可以获取时间。tv参数是struct timeval(在中指定):

    struct timeval {
        time_t      tv_sec;     /* seconds */
        suseconds_t tv_usec;    /* microseconds */
    };
    

    时间至少是32位,所以它可以存储小时。

        5
  •  0
  •   TJ-    14 年前

    如果精度(由像queryPerformanceTimer这样的win调用给出)不重要,我会使用gettimeofday方法(由@osgx建议)。

        6
  •  0
  •   j0k gauthamp    13 年前

    Boost timers 干得好。

    timer library提供一个timer类,用于测量已用时间,一个progress_timer类用于报告已用时间,一个progress_display类用于显示朝目标前进的指示。

        7
  •  0
  •   Pawan Kumar    11 年前
    #include <time.h>
    int main()
    {
    
    clock_t t1,t2;
    t1=clock();
    //write your code here
    
    t2=clock();
    float runningTime ((float)t2-(float)t1);
    //runningTime contains the time
    return 0;
    

    }