Does empty for loop cosume clock cycles?

naseeam
naseeam used Ask the Experts™
on
My target is based on Freescale 68HCS12 Microcontroller.  I need to create small dealys in my code.

for ( ;  counter != 0; counter-- )
{
       ;
}


Will this actually consume clock cycles or it'll just get optimized by Cosmic Compiler and I won't get any delay?


Thank you!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Neil RussellTechnical Development Lead

Commented:
No, it will be removed by the optimizer in the compiler and ignored.

Author

Commented:
Will following cause a delay?

for ( ;  counter != 0; counter-- )
{
       x++;
}
Senior Software Engineer (Avast)
Commented:
>> No, it will be removed by the optimizer in the compiler and ignored.

Hmmm... that's a bit of an assumption!

It may be removed by the optimiser but, then again, it may not. The answer to your questions is, yet it will if it is not optimised out. It you are trying to implement a busy wait be sure to put a sleep in the loop so that the process will give up its quantum immediately rather than hogging it and blocking other threads/processes.

for ( ;  counter != 0; counter-- )
{
       sleep(); // use whatever sleep function is provided by your OS.
}

Open in new window

Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

evilrixSenior Software Engineer (Avast)

Commented:
>> Will following cause a delay?
Rather than Q&A, it would be far simpler if you tell us what it is you are trying to do.

Author

Commented:
if x is volatile, will above code consume some clock cycles?
evilrixSenior Software Engineer (Avast)

Commented:
Quite possibly since the compiler probably won't be able to optimise away the use of x; however, it is really down to how the compiler's optimiser works. If it can figure out that ignoring x will cause no side-effects it might still optimise away the loop; however, I wouldn't like to put money either way -- your best be is to test it.

Compiler optimisation is a tricky subject and as programmers we're pretty poor at 2nd guessing them.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial