[英]Redirecting output of boost::timer::auto_cpu_timer
I'm widely using boost::timer::auto_cpu_timer
to measure the execution time of different functions and code blocks.我广泛使用boost::timer::auto_cpu_timer
来测量不同函数和代码块的执行时间。 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.出于跟踪目的,我想将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()); }
}
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
.除了基于boost::timer::cpu_timer
实现我自己的auto_cpu_timer
之外,我一直在环顾四周,找不到解决方案。 Is it possible to do directly on boost::timer::auto_cpu_timer
?是否可以直接在boost::timer::auto_cpu_timer
上执行?
I'm documenting it here because after googling and stackoverflowing for it I couldn't find the answer.我在这里记录它,因为在谷歌搜索和 stackoverflow 之后我找不到答案。
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:我不知道为什么我没有先关注它,但是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
For completeness, remember that std::clog
is initially associated to std::cerr
, which is usually also linked to the stdout
.为了完整起见,请记住std::clog
最初与std::cerr
相关联,而 std::cerr 通常也与stdout
相关联。 If the log file is optional, then std::clog
may be streaming to the incorrect destination.如果日志文件是可选的,则std::clog
可能正在流式传输到不正确的目的地。 If tracing should remain hidden except if the log file is specified, you can initially link std::clog
to a null buffer:如果跟踪应该保持隐藏,除非指定了日志文件,您可以最初将std::clog
链接到 null 缓冲区:
std::clog.rdbuf(nullptr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.