我正在广泛使用boost::timer::auto_cpu_timer来测量不同函数和代码块的执行时间。我正在使用宏来简化它的使用,当时我可以很容易地在生产中禁用它:
#include <boost/timer/timer.hpp>
#include <string>
#ifdef LOG_MEASURE_TIME
# define CPU_TIMER() boost::timer::auto_cpu_timer t_##__LINE__(cpuTimerFormat(__FUNCTION__, __LINE__))
#endif哪里
std::string cpuTimerFormat(const std::string &name, int line)
{
const std::string time = " %ws wall, %us user + %ss system = %ts CPU (%p%)\n";
return name + '@' + std::to_string(line) + time;
}为了便于跟踪,我想将boost::timer::auto_cpu_timer的输出从std::cout重定向到std::clog,这也是链接到一个可选日志文件的。
// log_path is a std::filesystem::path from application options or command-line arguments
std::ofstream log_file;
if (!log_path.empty()) {
log_file.open(log_path);
if (log_file.is_open()) { std::clog.rdbuf(log_file.rdbuf()); }
}我四处张望,除了基于auto_cpu_timer实现自己的boost::timer::cpu_timer之外,找不到其他解决方案。可以直接在boost::timer::auto_cpu_timer上做吗?
发布于 2020-06-01 17:10:28
我在这里记录它,因为在谷歌搜索和堆叠了它之后,我找不到答案。
我不知道为什么我不首先注意它,但是有一个boost::timer::auto_cpu_timer的构造函数接收一个std::ostream&,所以解决方案是非常直接的:
#include <iostream>
#ifdef LOG_MEASURE_TIME
# define CPU_TIMER() boost::timer::auto_cpu_timer t_##__LINE__(std::clog, cpuTimerFormat(__FUNCTION__, __LINE__))
#endif为了完整性,请记住std::clog最初与std::cerr相关联,而std::cerr通常也链接到stdout。如果日志文件是可选的,那么std::clog可能会流到不正确的目标。如果跟踪应该保持隐藏,除非指定了日志文件,您可以首先将std::clog链接到空缓冲区:
std::clog.rdbuf(nullptr);https://stackoverflow.com/questions/62137340
复制相似问题