Given a (inline void-returning nullary) function f
that doesn't have side effects:
inline void f() { /*...*/ }
Is it possible to write an inline function g
that calls f
but won't be optimized out by the implementation:
inline void g() { [[dont_optimize_this_away ???]] f(); }
Is there some way to tell the compiler "call f and inline the assembly, but don't optimize those instructions away"?
I don't think there is a way to do this in standard C 20. (or is there?)
...but is there a platform-specific way to do it on x86-64
with gcc
, clang
and/or msvc
? Some kind of instrinsic / compile builtin / attribute?
CodePudding user response:
According to this post,
you can use __attribute__((optimize("O0")))
like:
inline void __attribute__((optimize("O0"))) g() { [[dont_optimize_this_away ???]] f(); }
CodePudding user response:
Maybe this? Looking at the disassembly of release looks like it's still in there. (Windows pragma: https://docs.microsoft.com/en-us/cpp/preprocessor/optimize?view=msvc-170)
inline void f() {
//std::cout << "I do a thing";
}
#pragma optimize( "", off )
inline void g() {
f();
}
#pragma optimize( "", on )
int main()
{
g();
}
CodePudding user response:
There is a way. For example Google benchmark has benchmark::DoNotOptimize.
Just copy its implementation to your code and apply it for index variable for this dummy loop of yours for (int i = 0; i < 100; i );
form comment under a question.
Here is technical explanation how it works for gcc (note it is old source so name of function is different).