Redirecting output of boost::timer::auto_cpu_timer

216 views Asked by At

I'm widely using boost::timer::auto_cpu_timer to measure the execution time of different functions and code blocks. I'm using a macro to simplify its use at the time I can easily disable it in production:

#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

where

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;
}

For tracing purposes, I'd like to redirect the output of boost::timer::auto_cpu_timer from std::cout to std::clog, which is also linked to an optional log file.

// 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()); }
}

I've being looking around and couldn't find a solution for it other than implementing my own auto_cpu_timer based on boost::timer::cpu_timer. Is it possible to do directly on boost::timer::auto_cpu_timer?

1

There are 1 answers

0
cbuchart On BEST ANSWER

I'm documenting it here because after googling and stackoverflowing for it I couldn't find the answer.

I don't know why I didn't pay attention to it first, but there is a constructor for boost::timer::auto_cpu_timer that receives a std::ostream&, so the solution is quite straight forward:

#include <iostream>

#ifdef LOG_MEASURE_TIME
#  define CPU_TIMER() boost::timer::auto_cpu_timer t_##__LINE__(std::clog, cpuTimerFormat(__FUNCTION__, __LINE__))
#endif

For completeness, remember that std::clog is initially associated to std::cerr, which is usually also linked to the stdout. If the log file is optional, then std::clog may be streaming to the incorrect destination. If tracing should remain hidden except if the log file is specified, you can initially link std::clog to a null buffer:

std::clog.rdbuf(nullptr);