【问题标题】:How to measure run time of C++ code with older C++ (g++ 4.6.3) and older Boost library (1.46.1)?如何使用较旧的 C++ (g++ 4.6.3) 和较旧的 Boost 库 (1.46.1) 测量 C++ 代码的运行时间?
【发布时间】:2013-08-14 02:59:58
【问题描述】:

当使用“旧”版本时,在 C++ 中测量运行时间(挂墙时间)的推荐方法是什么? g++ 是 4.6.3(不是旧的,但不是 c++0x11,没有 -std=c++0x 开关),boost 也是旧的 1.46.1。

我尝试过测量 CPU 周期的 clock()。我试过 boost::timer() 也可以测量 CPU 周期。我必须使用 C 函数吗?

如果重要的话,这是带有 3.5 内核的 Ubuntu Linux。假设我无法添加 c++0x 开关或升级编译器或 boost 库,我想找出最佳实践。

作为参考,我使用下面的代码来测试不同的功能。结果大约是 0.2 秒,而不是我在 cin 调用时等待的多秒。

{
  boost::timer t;

  for (int i = 0; i < 99999999; i ++) ;

  std::string sin;
  std::cin >> sin;

  std::cout << t.elapsed() << std::endl;
}

【问题讨论】:

    标签: c++ gcc time


    【解决方案1】:

    使用 C/POSIX:

    clock_gettime(CLOCK_MONOTONIC, ...);
    

    将它包装到 C++ 函数中很方便,因此您不必处理 timespec 结构成员;最好将所有内容加入long longdouble

    例子:

    double getTimeInSeconds()
    {
        struct timespec result;
        if (clock_gettime(CLOCK_MONOTONIC, &result))
            throw ...something...;
        return result.tv_sec + (result.tv_nsec / 1000000000.);
    }
    

    您可能必须针对 librt 进行链接(即将-lrt 添加到链接器选项中)并且可能需要 pthreads。

    【讨论】:

      【解决方案2】:

      boost::timer 是由clock() 实现的。对于linux,time.h中包含的clock()的返回值是你的程序占用的cpu时间,而不是你的程序经过的时间,除以CLOCKS_PER_SEC 。它指的是man 3 clock。根据您的代码,std::cin &gt;&gt; sin; 不会占用 CPU 时间。

      增强计时器类

      class timer
      {
       public:
        timer() { _start_time = std::clock(); } // postcondition: elapsed()==0
         ...
        double elapsed() const                  // return elapsed time in seconds
          { return  double(std::clock() - _start_time) / CLOCKS_PER_SEC; }
      
       private:
        std::clock_t _start_time;
      }; 
      

      【讨论】:

      • 所有平​​台的接口都是一样的,但语义因平台而异。挂钟时间在 Windows 上测量,而 CPU 时间在类似 POSIX 的系统上测量。 reference of boost timer
      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2019-02-18
      • 2013-07-13
      相关资源
      最近更新 更多