重定向 boost::timer::auto_cpu_timer 的输出

Redirecting output of boost::timer::auto_cpu_timer

我广泛使用 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()); }
}

我环顾四周,除了基于 boost::timer::cpu_timer 实施我自己的 auto_cpu_timer 之外找不到解决方案。是否可以直接在 boost::timer::auto_cpu_timer 上执行?

我在这里记录它是因为在谷歌搜索和 Whosebuging 之后我找不到答案。

我不知道为什么我没有首先注意它,但是 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,后者通常也 link 关联到 stdout。如果日志文件是可选的,则 std::clog 可能会流式传输到错误的目的地。如果除非指定了日志文件,否则跟踪应保持隐藏,您最初可以 link std::clog 到空缓冲区:

std::clog.rdbuf(nullptr);