Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward variadic function arguments to another variadic function without cost

I have a variadic function LogDebug for log writing. Logging happens in two modes. My application forwards variadic arguments to another variadic function LogDebugEx in most cases hence that path needs to optimize. To be specific it takes 38% for vsnprintf for some of my requests on callgrind graph. Please note that this function called many times for a single request.

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

Question : I need to avoid copying whole argument list to zDesc array before forwarding to LogDebugEx function. Is there a way i can perfect forward variadic arguments coming to LogDebug into LogDebugEx function?

Any other fancy way to do this would also be fine without changing function calls to LogDebug. I have C++11 supported compiler GCC 4.9.3.

like image 989
PraAnj Avatar asked Jun 09 '26 23:06

PraAnj


1 Answers

If we have c++11, why mess around with variadic argument lists?

#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
    }
}
like image 110
Richard Hodges Avatar answered Jun 11 '26 14:06

Richard Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!