典型的基于 LOG() 宏的日志记录解决方案可能如下所示:
#define LOG(msg) \
std::cout << __FILE__ << "(" << __LINE__ << "): " << msg << std::endl
这允许程序员使用方便且类型安全的流操作符创建数据丰富的消息:
string file = "blah.txt";
int error = 123;
...
LOG("Read failed: " << file << " (" << error << ")");
// Outputs:
// test.cpp(5): Read failed: blah.txt (123)
问题是这会导致编译器内联多个 ostream::operator<< 调用。这会增加生成的代码并因此增加函数大小,我怀疑这可能会损害指令缓存性能并阻碍编译器优化代码的能力。
这是一个“简单”的替代方法,它用对可变参数模板函数的调用替换内联代码:
*********
解决方案#2:可变模板函数 *********
#define LOG(...) LogWrapper(__FILE__, __LINE__, __VA_ARGS__)
// Log_Recursive wrapper that creates the ostringstream
template<typename... Args>
void LogWrapper(const char* file, int line, const Args&... args)
{
std::ostringstream msg;
Log_Recursive(file, line, msg, args...);
}
// "Recursive" variadic function
template<typename T, typename... Args>
void Log_Recursive(const char* file, int line, std::ostringstream& msg,
T value, const Args&... args)
{
msg << value;
Log_Recursive(file, line, msg, args...);
}
// Terminator
void Log_Recursive(const char* file, int line, std::ostringstream& msg)
{
std::cout << file << "(" << line << "): " << msg.str() << std::endl;
}
编译器会根据需要根据消息参数的数量、种类和顺序自动生成模板函数的新实例。
好处是每个呼叫站点的指令更少。缺点是用户必须将消息部分作为函数参数传递,而不是使用流操作符组合它们:
LOG("Read failed: ", file, " (", error, ")");
*********
解决方案#3:表达式模板 *********
在@DyP 的建议下,我创建了一个使用表达式模板的替代解决方案:
#define LOG(msg) Log(__FILE__, __LINE__, Part<bool, bool>() << msg)
template<typename T> struct PartTrait { typedef T Type; };
// Workaround GCC 4.7.2 not recognizing noinline attribute
#ifndef NOINLINE_ATTRIBUTE
#ifdef __ICC
#define NOINLINE_ATTRIBUTE __attribute__(( noinline ))
#else
#define NOINLINE_ATTRIBUTE
#endif // __ICC
#endif // NOINLINE_ATTRIBUTE
// Mark as noinline since we want to minimize the log-related instructions
// at the call sites
template<typename T>
void Log(const char* file, int line, const T& msg) NOINLINE_ATTRIBUTE
{
std::cout << file << ":" << line << ": " << msg << std::endl;
}
template<typename TValue, typename TPreviousPart>
struct Part : public PartTrait<Part<TValue, TPreviousPart>>
{
Part()
: value(nullptr), prev(nullptr)
{ }
Part(const Part<TValue, TPreviousPart>&) = default;
Part<TValue, TPreviousPart> operator=(
const Part<TValue, TPreviousPart>&) = delete;
Part(const TValue& v, const TPreviousPart& p)
: value(&v), prev(&p)
{ }
std::ostream& output(std::ostream& os) const
{
if (prev)
os << *prev;
if (value)
os << *value;
return os;
}
const TValue* value;
const TPreviousPart* prev;
};
// Specialization for stream manipulators (eg endl)
typedef std::ostream& (*PfnManipulator)(std::ostream&);
template<typename TPreviousPart>
struct Part<PfnManipulator, TPreviousPart>
: public PartTrait<Part<PfnManipulator, TPreviousPart>>
{
Part()
: pfn(nullptr), prev(nullptr)
{ }
Part(const Part<PfnManipulator, TPreviousPart>& that) = default;
Part<PfnManipulator, TPreviousPart> operator=(const Part<PfnManipulator,
TPreviousPart>&) = delete;
Part(PfnManipulator pfn_, const TPreviousPart& p)
: pfn(pfn_), prev(&p)
{ }
std::ostream& output(std::ostream& os) const
{
if (prev)
os << *prev;
if (pfn)
pfn(os);
return os;
}
PfnManipulator pfn;
const TPreviousPart* prev;
};
template<typename TPreviousPart, typename T>
typename std::enable_if<
std::is_base_of<PartTrait<TPreviousPart>, TPreviousPart>::value,
Part<T, TPreviousPart> >::type
operator<<(const TPreviousPart& prev, const T& value)
{
return Part<T, TPreviousPart>(value, prev);
}
template<typename TPreviousPart>
typename std::enable_if<
std::is_base_of<PartTrait<TPreviousPart>, TPreviousPart>::value,
Part<PfnManipulator, TPreviousPart> >::type
operator<<(const TPreviousPart& prev, PfnManipulator value)
{
return Part<PfnManipulator, TPreviousPart>(value, prev);
}
template<typename TPart>
typename std::enable_if<
std::is_base_of<PartTrait<TPart>, TPart>::value,
std::ostream&>::type
operator<<(std::ostream& os, const TPart& part)
{
return part.output(os);
}
表达式模板解决方案允许程序员使用熟悉的方便且类型安全的流操作符:
LOG("Read failed: " << file << " " << error);
但是,当Part<A, B>
内联创建时,不会进行 operator<< 调用,这给我们带来了两全其美的好处:方便且类型安全的流式操作符 + 更少的指令。带有 -O3 的 ICC13 生成以下汇编代码:
movl $.L_2__STRING.3, %edi
movl $13, %esi
xorl %eax, %eax
lea 72(%rsp), %rdx
lea 8(%rsp), %rcx
movq %rax, 16(%rsp)
lea 88(%rsp), %r8
movq $.L_2__STRING.4, 24(%rsp)
lea 24(%rsp), %r9
movq %rcx, 32(%rsp)
lea 40(%rsp), %r10
movq %r8, 40(%rsp)
lea 56(%rsp), %r11
movq %r9, 48(%rsp)
movq $.L_2__STRING.5, 56(%rsp)
movq %r10, 64(%rsp)
movq $nErrorCode.9291.0.16, 72(%rsp)
movq %r11, 80(%rsp)
call _Z3LogI4PartIiS0_IA2_cS0_ISsS0_IA14_cS0_IbbEEEEEENSt9enable_ifIXsr3std10is_base_ofI9PartTraitIT_ESA_EE5valueEvE4typeEPKciRKSA_
总共有 19 条指令,包括一个函数调用。流式传输的每个附加参数似乎都增加了 3 条指令。编译器根据消息部分的数量、种类和顺序创建不同的 Log() 函数实例化,这解释了奇怪的函数名称。
*********
解决方案 #4:CATO 的表达式模板 *********
这是 Cato 的出色解决方案,通过调整来支持流操纵器(例如 endl):
#define LOG(msg) (Log(__FILE__, __LINE__, LogData<None>() << msg))
// Workaround GCC 4.7.2 not recognizing noinline attribute
#ifndef NOINLINE_ATTRIBUTE
#ifdef __ICC
#define NOINLINE_ATTRIBUTE __attribute__(( noinline ))
#else
#define NOINLINE_ATTRIBUTE
#endif // __ICC
#endif // NOINLINE_ATTRIBUTE
template<typename List>
void Log(const char* file, int line,
LogData<List>&& data) NOINLINE_ATTRIBUTE
{
std::cout << file << ":" << line << ": ";
output(std::cout, std::move(data.list));
std::cout << std::endl;
}
struct None { };
template<typename List>
struct LogData {
List list;
};
template<typename Begin, typename Value>
constexpr LogData<std::pair<Begin&&, Value&&>> operator<<(LogData<Begin>&& begin,
Value&& value) noexcept
{
return {{ std::forward<Begin>(begin.list), std::forward<Value>(value) }};
}
template<typename Begin, size_t n>
constexpr LogData<std::pair<Begin&&, const char*>> operator<<(LogData<Begin>&& begin,
const char (&value)[n]) noexcept
{
return {{ std::forward<Begin>(begin.list), value }};
}
typedef std::ostream& (*PfnManipulator)(std::ostream&);
template<typename Begin>
constexpr LogData<std::pair<Begin&&, PfnManipulator>> operator<<(LogData<Begin>&& begin,
PfnManipulator value) noexcept
{
return {{ std::forward<Begin>(begin.list), value }};
}
template <typename Begin, typename Last>
void output(std::ostream& os, std::pair<Begin, Last>&& data)
{
output(os, std::move(data.first));
os << data.second;
}
inline void output(std::ostream& os, None)
{ }
正如 Cato 所指出的,与上一个解决方案相比,它的好处是它可以减少函数实例化,因为 const char* 专门化处理所有字符串文字。它还导致在调用站点生成的指令更少:
movb $0, (%rsp)
movl $.L_2__STRING.4, %ecx
movl $.L_2__STRING.3, %edi
movl $20, %esi
lea 212(%rsp), %r9
call void Log<pair<pair<pair<pair<None, char const*>, string const&>, char const*>, int const&> >(char const*, int, LogData<pair<pair<pair<pair<None, char const*>, string const&>, char const*>, int const&> > const&)
如果您能想到任何方法来提高此解决方案的性能或可用性,请告诉我。