Force compiler to not optimize side-effect-less statements
c++, optimization
Solution
Compilers are unfortunately allowed to optimise as much as they like, even without any explicit switches, if the code behaves as if no optimisation takes place. However, you can often trick them into not doing so if you indicate that value might be used later, so I would change your code to:
int float_to_int(float f)
{
return static_cast<int>(f); // has no side-effects
}
As others have suggested, you will need to examine the assemnler output to check that this approach actually works.
Problem
I was reading some old game programming books and as some of you might know, back in that day it was usually faster to do bit hacks than do things the standard way. (Converting `float` to `int`, mask sign bit, convert back for absolute value, instead of just calling `fabs()`, for example) Nowadays is almost always better to just use the standard library math functions, since these tiny things are hardly the cause of most bottlenecks anyway. But I still want to do a comparison, just for curiosity's sake. So I want to make sure when I profile, I'm not getting skewed results. As such, I'd like to make sure the compiler does not optimize out statements that have no side effect, such as: ``` void float_to_int(float f) { int i = static_cast<int>(f); // has no side-effects } ``` Is there a way to do this? As far as I can tell, doing something like `i += 10` will still have no side-effect and as such won't solve the problem. The only thing I can think of is having a global variable, `int dummy;`, and after the cast doing something like `dummy += i`, so the value of `i` is used. But I feel like this dummy operation will get in the way of the results I want. I'm using Visual Studio 2008 / G++ (3.4.4). Edit To clarify, I would like to have all optimizations maxed out, to get good profile results. The problem is that with this the statements with no side-effect will be optimized out, hence the situation. Edit Again To clarify once more, read this: I'm not trying to micro-optimize this in some sort of production code. We all know that the old tricks aren't very useful anymore, I'm merely curious how not useful they are. Just plain curiosity. Sure, life could go on without me knowing just how these old hacks perform against modern day CPU's, but it never hurts to know. So telling me "these tricks aren't useful anymore, stop trying to micro-optimize blah blah" is an answer completely missing the point. I know they aren't useful, I don't use them. Premature quoting of Knuth is the root of all annoyance.