Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Tell C++ to not optimize away an expression that's thrown away?

I want to profile a series of matrice operations to get an idea of how much time they'll take. (I'm much less inclined to think about optimizations when I'm reminded how stupidly fast the CPU can chew through instructions, eheh)

for(int n = 0; n < times; ++n){
    // scrambled to miss the cache on purpose
    matrix[ rand()%matrixLen ] * matrix[ rand()%matrixLen ];
}

My compiler keeps optimizing this expression away. Is there any way to get it to actually execute this code while still retaining all other optimizations?

like image 678
Anne Quinn Avatar asked Jul 21 '14 20:07

Anne Quinn


People also ask

How to avoid compiler optimization in C?

But in practice gcc will ignore the statement by dead store elimination. In order to prevent gcc optimizing it, I re-write the statement as follows: volatile int tmp; tmp = pageptr[0]; pageptr[0] = tmp; It seems the trick works, but somewhat ugly.

How do I keep my compiler from optimizing variables?

Click on Override Build Options. Select the compiler. Under the Optimization category change optimization to Zero. When done debugging you can uncheck Override Build Options for the file.

How do I disable gcc optimization?

The gcc option -O enables different levels of optimization. Use -O0 to disable them and use -S to output assembly. -O3 is the highest level of optimization.


2 Answers

Most likely, you're going to need to use a #pragma. How you do that is entirely compiler dependent (sorry), but there is a certain amount of commonality in the process:

// save your current options
#if SPEEDTEST
#pragma GCC push_options 
#pragma GSS optimize("whatever the settings are")
#endif

// ... your code

// restore options
#if SPEEDTEST
#pragma GCC pop_options
#endif

or in your case:

#if SPEEDTEST
#pragma optimize("", off)
#endif

// ... your code

#if SPEEDTEST
#pragma optimize("", on)
#endif    

NB: you can't use some #pragma statements within a function

like image 155
plinth Avatar answered Oct 02 '22 15:10

plinth


You ignore the result of the computation, hence the compiler can remove it. Just store the result:

<yourMatrixType> result = matrix[ rand()%matrixLen ];
for(int n = 0; n < times; ++n){
    // scrambled to miss the cache on purpose
    result *= matrix[ rand()%matrixLen ];
}

That should prevent the compiler from removing the computation.

like image 42
SniperAlarm Avatar answered Oct 02 '22 15:10

SniperAlarm