c++ - 如何同时使用boost auto_cpu_timer和progress_display?

标签 c++ boost timer

我想使用 boost auto_cpu_timer 来显示我的完整代码需要运行的时间。此外,我想使用 progress_display 查看循环的进度。

似乎存在命名空间冲突,因为 Boost 有两个计时器类,其中 progress_display 来自旧的、现已弃用的库。

http://www.boost.org/doc/libs/1_51_0/libs/timer/doc/index.html

还有,有什么办法可以做到这一点吗?以下示例显示了我正在尝试做的事情。使用 AUTOPROG 都可以正常工作,但同时使用会导致错误消息。

Main: 使用 g++ -lboost_timer main.cc -o time 编译

#define AUTO
#define PROG

#ifdef  PROG
#include <boost/progress.hpp>
#endif     //----  PROG  -----

#ifdef  AUTO
#include <boost/timer/timer.hpp>
#endif     //----  AUTO  -----

#include <cmath>

int main()
{
#ifdef  AUTO
    boost::timer::auto_cpu_timer t;
#endif     //----  AUTO  -----

    long loops = 100000000;

#ifdef  PROG
    boost::progress_display pd( loops );
#endif     //----  PROG  -----

    //long loop to burn some time
    for (long i = 0; i < loops; ++i)
    {
        std::sqrt(123.456L);
#ifdef  PROG
        ++pd;
#endif     //----  PROG  -----
    }

    return 0;
}

错误日志:

/usr/include/boost/timer/timer.hpp:38:1: error: ‘namespace boost::timer { }’ redeclared as different kind of symbol
/usr/include/boost/timer.hpp:45:1: error: previous declaration of ‘class boost::timer’
/usr/include/boost/timer/timer.hpp: In member function ‘std::string boost::timer::cpu_timer::format(short int, const std::string&) const’:
/usr/include/boost/timer/timer.hpp:74:34: error: ‘format’ is not a member of ‘boost::timer’
/usr/include/boost/timer/timer.hpp: In member function ‘std::string boost::timer::cpu_timer::format(short int) const’:
/usr/include/boost/timer/timer.hpp:76:34: error: ‘format’ is not a member of ‘boost::timer’
main.cc: In function ‘int main()’:
main.cc:17:2: error: ‘auto_cpu_timer’ is not a member of ‘boost::timer’
main.cc:17:31: error: expected ‘;’ before ‘t’

最佳答案

当您包含 boost/progress.hpp 时,C++ 编译器会将 boost::timer 的定义视为 class timer 定义在 boost/timer.hpp 包含在 boost/progress.hpp 中。

当您包含 boost/time/timer.hpp 时,C++ 编译器会将 boost::timer 的另一个定义视为命名空间,这就是错误的原因.

如果你真的想使用它,解决方案是通过宏重命名其中一个 boost::timer 。但是因为 namespace boost::timer 包含在 header 之外实现的函数(如 std::string format(const cpu_times& times, short places, const std::string& format)) 你必须重命名 class boost::timer。所以你的代码将是这样的:

#ifdef  PROG
#define timer   timer_class
#include <boost/progress.hpp>
#undef timer
#endif     //----  PROG  -----

#ifdef  AUTO
#include <boost/timer/timer.hpp>
#endif     //----  AUTO  -----

关于c++ - 如何同时使用boost auto_cpu_timer和progress_display?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12760828/

相关文章:

c++ - 如何用奇偶规则填充多边形?

c++ - 带 if 条件的作用域锁

c# - .NET 计时器,它们是在准确的时间间隔触发还是在处理 + 间隔后触发

c - 等待信号,然后继续执行

C++ : reading content from a file in a specific format

c++ - Mac 上 make 失败

c++ - 传递给线程的 lambda 中的调用函数

c++ - Boost图库: Get edge_descriptor or access edge by index of type int

C++ 无法解析变量 BOOST_FOREACH

java - 定时器任务执行一次后如何停止