Sometimes when writing benchmarks I have found it useful to use an "opaque" function which prevents the optimizer from completely removing a variable. On gcc and clang I have an implementation using inline assembly which seems to work as I want in all cases I have tested so far. Here is a simple example of what I am interested in (example on godbolt):
template<class T>
void opaque(T&& t)
{
asm volatile("" : "+r" (t));
}
int test(int a) { return a + 5; }
int main()
{
int a = 10;
opaque(a);
return test(a);
}
The above code generates the following assembly:
movl $10, %eax
addl $5, %eax
ret
whereas, without the opaque function it generates:
movl $15, %eax
ret
How would I write an equivalent to the opaque function for the visual studio compiler (specifically 2013)?
Select the compiler. Under the Optimization category change optimization to Zero. When done debugging you can uncheck Override Build Options for the file. In the latter case the volatile defined inside the function can get optimized out quite often. ...
Open the project's Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio. Select the Configuration Properties > C/C++ > Optimization property page. Modify the Optimization property.
Compilers provides ways to control their optimizer. gcc provides pragma GCC as a way to control temporarily the compiler behavior. By using pragma GCC optimize("O0") , the optimization level can be set to zero, which means absolutely no optimize for gcc.
By optimizing an executable, you can achieve a balance between fast execution speed and small code size. This topic discusses some of the mechanisms that Visual Studio provides to help you optimize code.
I know it's very late for answering this but I'm having a similar problem. My constellation is VSCode + CMake + MSVC, and I've done some researching and found the following Visual Studio article: https://developercommunity.visualstudio.com/t/compiler-optimizes-out-some-variables-in-release-b/276808
If you are concerned that the compiler is optimizing in the root of a benchmark, there are two general approaches which I find effective: 1. Strategic use of volatile variables to prevent the above optimizations from kicking in. 2. Disable optimizations around the "main" function with #pragma optimize("", off) / #pragma optimize("", on). I prefer option 2, where I find the intent more clear.
I tested the option with #pragma optimize("", on / off) around the main function and it actually works.
The other option is of course disable optimization entirely with /Od tag for compiler. (https://docs.microsoft.com/en-us/cpp/build/reference/od-disable-debug?view=msvc-170)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With