Home > other >  How can I optimize just one function if optimization is switched off for the whole project?
How can I optimize just one function if optimization is switched off for the whole project?

Time:10-30

I work on a large project which has optimization disabled. The vast majority of the devs prefer it this way because our project is I/O bound anyway and it makes dump analysis easier. Recently I've started looking replacing our printf based tracing mechanism with std::format. However, there's a problem, in my profiling, std::format is faster than our current tracing with optimization on but more than 2000% slower with optimization off. Using it would actually make a significant performance dent.

This has lead me to wonder if I could turn optimization on for just one function or perhaps just one static library. However, I'm struggling to work out how. The problem is that the nature std::format means that any tracing function you wrote to use it would have to forward on the template arguments and must therefore be a template its self. E.g.:

template<typename... Args>
void Trace(std::_Fmt_wstring<Args& ...> fmt, Args& ...args)
{
    wchar_t buf[0x1000];
    std::format_to(buf, fmt, args...);
    // Pass the buffer to the tracing framework
}

Because it's a template, it's header based and I can't put the compiled tracing code in a static library. It'll get instantiated in the non-optimized code where it's called.

How can I make this function optimized? I've tried #pragma optimize however it doesn't help because I need to not only optimize the function its self but the code generated by std::format_to.

Any ideas?

CodePudding user response:

You mention that one challenge is that they're template functions. You could try wrapping the library headers with your own headers that declare the specific specializations that you use as extern (to prevent implicit instantiation of the templates when they get used), and then create a static library where you instantiate those specializations, and compile the static library with whichever optimization level you want (I'm not that familiar with MSVC, but you might need to check whether there are any compatibility needs of which runtime libraries are being linked to in the static library and your own compiled binaries). Then in your project, you include your wrapped versions of the library headers and link against the static library.

CodePudding user response:

The vast majority of the devs prefer it this way because our project is I/O bound anyway and it makes dump analysis easier

This is what the /Zo flag was invented to solve for. It makes debugging retail code way easier. Not perfect, but far better than without it.

  • Related