
Best Answer j2inet, 09 April 2013 - 02:50 PM
I've just come up with a solution for my needs. I'm using a spin wait.
When my program starts up I time how long it takes to perform 2^20 increments (this way the delay should work across different processor clock waits). Then I just use this information to decide how many cycles to wait. For the timing values that I need it looks like this should work. I've not accounted for the overhead of making the call to the method but I hope that it will be within tolerance for my application.
Source code is below. The default calibration value is from a Netduino Plus 2 with the source code running in debug mode. As long as you call calibrate before using it the default value should not matter.
public class SpinWaitTimer { double _cyclesPerSecond = 112262.2255516001; public double CyclesPerSecond { get { return _cyclesPerSecond; } set { _cyclesPerSecond = value; } } public SpinWaitTimer() { } public void Calibrate() { const int CYCLE_COUNT = 1048576; int dummyValue = 0; DateTime startTime = DateTime.Now; for (int i = 0; i < CYCLE_COUNT; ++i) { ++dummyValue; } DateTime endTime = DateTime.Now; TimeSpan timeDifference = endTime.Subtract(startTime); _cyclesPerSecond = ((double)CYCLE_COUNT / (double)timeDifference.Ticks)*10000000d; } public void WaitSeconds(double sec) { int cycleCount = (int)((sec * CyclesPerSecond)); int dummyValue = 0; for (int i = 0; i < cycleCount; ++i) { ++dummyValue; } } public void WaitMilliseconds(double microseconds) { int cycleCount = (int)(_cyclesPerSecond * CyclesPerSecond / 1000d); int dummyValue = 0; for (int i = 0; i < cycleCount; ++i) { ++dummyValue; } } public void WaitMicroseconds(double microseconds) { int cycleCount = (int)(_cyclesPerSecond * CyclesPerSecond / 1000000d); int dummyValue = 0; for (int i = 0; i < cycleCount; ++i) { ++dummyValue; } } }Go to the full post
