我想使用boost auto_cpu_timer来显示我的完整代码需要运行的时间.另外,我希望看到我的循环使用的进度progress_display.
似乎有一个命名空间的混淆,因为Boost有两个计时器类,其中progress_display来自旧的,现已弃用的库.
http://www.boost.org/doc/libs/1_51_0/libs/timer/doc/index.html
仍有,有办法实现这一目标吗?以下示例显示了我正在尝试做的事情.使用任何一个AUTO或PROG工作正常,但两者一起导致错误消息.
主要:编译用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;
}
Run Code Online (Sandbox Code Playgroud)
错误日志:
/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’
Run Code Online (Sandbox Code Playgroud)
如果包括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包含在标题之外实现的函数(如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 -----
Run Code Online (Sandbox Code Playgroud)