3

I need to have a function busy-wait.

for(long int j=0; j<50000000; ++j)
  ;

When I compile in release mode, this gets optimized out. Other than compiling in debug mode, is there some way to cause this to not get optimized out? I don't particularly care about the actual number of the loop, but it must be a noticeable busy-delay.

Baruch
  • 20,590
  • 28
  • 126
  • 201

1 Answers1

5

I don't know why you need to keep the CPU busy, but let's assume that you really have a good reason, like making sure you keep the CPU busy so it doesn't think about that breakup it went through last week and get all depressed but I digress...

The problem you are seeing is that the compiler performs "dead code elimination": it sees that the loop does nothing (i.e. has no side-effects) and so cuts it out. So you could make it have a side-effect.

A simple solution would be this function:

void busywait(long iterations)
{
    for(volatile long i = 0; i != iterations; i++)
        ;
}

By marking i as volatile you are ensuring that the loop has side-effects, since stores to volatile objects (i.e. the incrementing we perform) are treated as having side-effects.

Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
  • It now gets optimized to the equivalent of `i += iterations;` – Baruch Dec 22 '12 at 19:11
  • You could always selectively disable optimizations for that particular function. But in all seriousness, you can tweak the code of the loop so that it has side-effects that the compiler cannot optimize away. – Nik Bougalis Dec 23 '12 at 01:36
  • As a sidenote (four months after the fact) I find it hard to believe that a conforming compiler would optimize the loop to the equivalent of `i += iterations` because every single `+=` will have a side-effect that the standard requires be visible, and coalescing them into one `+=` misses out on `iterations - 1` side-effects. – Nik Bougalis Apr 04 '13 at 20:47