Jump to content
Sign in to follow this  
caneralp

Optimization Problem

Recommended Posts

Hello,


 


I have a problem with optimization. Can anyone help me?


 


my code is below which is for loop and delaying.


 


volatile unsigned int b;

 

b = 30000;

do

{

b--;

}while(b != 0);

 

normally unless I define b as a volatile variable, it doesnt work, Can anyone explain why it doesnt work?

 

Also when I debug step by step, It works. Also without this loop it works but I can not see the changes.

 

Thanks

Share this post


Link to post
Share on other sites

Without volatile: The compiler recognises that the loop has no net effect and that the end result will be that b==0. Therefore, the loop is replaced with an assignment.

 

With volatile: the compiler presumes that, even if it can't see it, something, somewhere, may be looking at the value of b other than the code in the loop. Therefore, it a.) compiles the code exactly as written, with b.) no optimizations, and c.) not using a register for the variable (it will always be in RAM, with the associated time penalty for access)

Share this post


Link to post
Share on other sites

why use delay loops if you can use timers and low power mode to achieve a similar goal?

 

Also, if you really need a busy wait it's better to use the __delay_cycles() intrinsic function. That way the compiler definitely won't optimise it out and the length of the delay is clearly defined.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...