Hi,
I recently had a project using a Netduino where I needed to pause execution for 500 μs after sending a signal to a peripheral. The standard Thread.Sleep only offers twice that pause duration of 1000 μs or 1ms. This was all I was able to achieve, which resulted in a sub-optimal result.
I wonder if anyone has any thoughts on strategies to achieve a sub 1ms Thread.Sleep, maybe using a native call or similar?
Thanks
Andy
Strategies for sub 1ms Thread.Sleep
Started by andybareweb, May 12 2011 02:43 PM
4 replies to this topic
#1
Posted 12 May 2011 - 02:43 PM
#3
Posted 12 May 2011 - 03:11 PM
Hi Andy,
Sleep times that are less than 1ms are not exact, but here's a 100% managed code strategy (written off the top of my head, not tested):
A few notes for optimization:
Sleep times that are less than 1ms are not exact, but here's a 100% managed code strategy (written off the top of my head, not tested):
void SleepMicroseconds(int microsecondsToWait) { // TODO: calibrate this call by subtracting the number of microseconds of "overhead" microSecondsToWait -= KNOWN_MICROSECONDS_OF_OVERHEAD; // create an event which will be raised when our sleep time is over. AutoResetEvent sleepCompletedEvent = new AutoResetEvent(false); // start a timer to count down our sleep time. Timer sleepTimer = new Timer(delegate(object state) { // signal that our timer has completed. sleepCompletedEvent.Set(); }, sleepCompletedEvent, new TimeSpan(microsecondsToWait * (TimeSpan.TicksPerMillisecond / 1000)), new TimeSpan(0,0,0,0,-1)); // TODO: verify that the period means "do not call twice." // wait for our timer to complete. sleepCompletedEvent.WaitOne(); }
A few notes for optimization:
- You'll want to measure the amount of overhead the managed code adds to the time -- and subtract that from the millisecondsToWait variable on the first line.
- If you only need one timer in total, you can create the sleepTimer and sleepCompletedEvent classes once -- and then reuse them. This will decrease the overhead.
#4
Posted 12 May 2011 - 03:47 PM
Thanks guys, I'll try to speed it up using those techniques!
#5
Posted 08 March 2012 - 10:26 AM
Hi!
Is the "SleepMicroseconds" function working good? Anyone tried it?
Best Regards
Jansson
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users