I need a function to run at a precise time within +/- 1ms. I have tried the following but end up with a 15ms minimum time between execution.
void Main()
{
System.Timers.Timer timer = new System.Timers.Timer(1); // executes every 15ms
timer.Elapsed += new System.Timers.ElapsedEventHandler(myFunction);
System.Timers.Timer timer2 = new System.Timers.Timer(5); // executes every 15ms
timer2.Elapsed += new System.Timers.ElapsedEventHandler(myFunction);
System.Timers.Timer timer2 = new System.Timers.Timer(20); // executes every 31ms
timer3.Elapsed += new System.Timers.ElapsedEventHandler(myFunction);
timer.Start();
timer2.Start();
timer3.Start();
}
void myFunction()
{
doWord();
}
using Thread.Sleep() obtains the same results.
Synopsis of application.
I will be reading in a file that contains 1553 messages (each with a timestamp). I will need to replay these messages with as close as possible timing that the file contains. The timestamps for the messages are recorded in microsec, but I will only need msec accuracy.
This is done using a DDC 1553 card (PCI Card). I have an analyzer which allows me to view the messages including the delta time between messages to measure my accuracy.
The machine I’m using has a QuadCore with hyperthreading. Using a for(int i=0; …..) I can get accuracy to with .5msec. However this is very inefficient and would prefer to use a more realistic and even more portable method if possible.
.NET, C#, and even Windows in general are not realtime OSes suitable for very fine timing.
The worst options include using the
Timerclasses andThread.Sleep().You can measure timing fairly accurately using the
Stopwatchclass, but in terms of accurately waiting for a set amount of time to pass.. there’s no built-in mechanism.If you could outline exactly what you are trying to do, assuming it’s not motion control, hardware interfacing etc, there is probably a better solution than relying on very accurate timers.
Update; Neal: if you are interfacing with hardware in a timing-sensitive way, you should use a different solution. You can do a tight loop with
Stopwatch, but it will use lots of CPU for as long as you do. And it won’t be accurate enough, probably. E.g.: a PIC chip, an FPGA, an I/O card or interface, anything else basically.