将可变参数函数参数转发给另一个可变参数函数而无需成本

问题描述 投票:2回答:1

我有一个可变函数LogDebug用于日志写作。记录以两种模式进行。我的应用程序在大多数情况下将可变参数转发给另一个可变函数LogDebugEx,因此该路径需要优化。具体来说,对于我在callgrind图上的一些请求,vsnprintf需要38%。请注意,此功能可针对单个请求多次调用。

void LogDebug(const char* zFormat, ...)
{
    char zDesc[5000];
    va_list ap;
    va_start(ap, zFormat);
    vsnprintf(zDesc, 5000, zFormat, ap);  // Need to optimize in remode mode.
    va_end(ap);

    if (m_logMode == LOG_MODE_LOCAL)    // Does not need to optimize this mode.
    {
        // This mode is not interested.
    }
    else // m_logMode == LOG_MODE_REMOTE, critical path
    {
        LogDebugEx("%s", zDesc);   // Forwarded to new variadic function
    }
}

问题:在转发到zDesc函数之前,我需要避免将整个参数列表复制到LogDebugEx数组。有没有办法我可以完善向LogDebug进入LogDebugEx函数的可变参数?

如果不改变对LogDebug的函数调用,任何其他奇特的方法也可以。我有C++11支持编译器GCC 4.9.3

c++ c++11 optimization variadic-functions perfect-forwarding
1个回答
9
投票

如果我们有c ++ 11,为什么要乱用可变参数列表呢?

#include <utility>

extern enum {LOG_MODE_LOCAL, LOG_MODE_REMOTE} m_logMode;

extern void LogDebugEx(const char*, ...);

template<class...Args>
void LogDebug(const char* zFormat, Args&&...args)
{

    if (m_logMode == LOG_MODE_LOCAL)    // Does not need to optimize this mode.
    {
        char zDesc[5000];
        snprintf(zDesc, 5000, zFormat, args...);  
        // do what you have to do here
    }
    else // m_logMode == LOG_MODE_REMOTE, critical path
    {
        LogDebugEx(zFormat, std::forward<Args>(args)...);   // Forwarded to new variadic function
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.