首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重定向boost::timer::auto_cpu_timer输出

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

Stack Overflow用户
提问于 2020-06-01 17:10:28
回答 1查看 151关注 0票数 0

我正在广泛使用boost::timer::auto_cpu_timer来测量不同函数和代码块的执行时间。我正在使用宏来简化它的使用,当时我可以很容易地在生产中禁用它:

代码语言:javascript
复制
#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

哪里

代码语言:javascript
复制
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,这也是链接到一个可选日志文件的。

代码语言:javascript
复制
// 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上做吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-01 17:10:28

我在这里记录它,因为在谷歌搜索和堆叠了它之后,我找不到答案。

我不知道为什么我不首先注意它,但是有一个boost::timer::auto_cpu_timer的构造函数接收一个std::ostream&,所以解决方案是非常直接的:

代码语言:javascript
复制
#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链接到空缓冲区:

代码语言:javascript
复制
std::clog.rdbuf(nullptr);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62137340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档