??? 06/19/09 17:16 Read: times |
#166260 - re: unsigned Responding to: ???'s previous message |
Per Westermark said:
With unsigned integers, you don't need to take rollovers into account unless you need long delays in relation to the rollover frequency. Hmmm ... time for an experiment. So assume we count down, and my starting timer count is 0x100, and my desired period is 0x1234. I need to compare against 0x100-0x1234, which rolls over. So does the compiler saturate at 0, or does it roll over? Here's what I'm doing, which handles rollover. I think I added the rollover handling code because I didn't know what the compiler would do in the rollover case. (To me, "undefined operation" may include a black hole swallowing the world, and I do my best to avoid this.) lastTick = timer_GetCount(); for(;;) { thisTick = timer_GetCount(); if (lastTick > thisTick) { // normally count down moduloTick = lastTick - thisTick; } else { // handle rollover: moduloTick = lastTick + 0xFFFFFFFF - thisTick; } // should we process? if (moduloTick > INTERVAL) { lastTick = thisTick; // save new count as old doWhatNeedsToBeDone(); // process stuff } } // forever And now that I look at it, a better solution, which saves the compare and subtract each time though the loop, would be something like: timeout = timer_GetCount(); if (timeout < INTERVAL) { // handle rollover: timeout = 0xFFFFFFFF - INTERVAL - timeout; } else { timeout -= INTERVAL; } for(;;) { thisTick = timer_GetCount(); if (thisTick == timeout) { // compute timeout for next interval: if (thisTick < INTERVAL) { timeout = 0xFFFFFFFF - INTERVAL - timeout; } else { timeout = thisTick - INTERVAL; } doWhatNeedsToBeDone(); // process stuff } } // forever One suspects that the compiler will optimize the subtraction of two constants 0xFFFFFFFF - INTERVAL. -a |