Both System.Timers.Timer
and System.Threading.Timer
fire at intervals that are considerable different from the requested ones.
For example:
new System.Timers.Timer(1000d / 20);
yields a timer that fires 16 times per second, not 20.
To be sure that there are no side-effects from too long event handlers, I wrote this little test program:
int[] frequencies = { 5, 10, 15, 20, 30, 50, 75, 100, 200, 500 };
// Test System.Timers.Timer
foreach (int frequency in frequencies)
{
int count = 0;
// Initialize timer
System.Timers.Timer timer = new System.Timers.Timer(1000d / frequency);
timer.Elapsed += delegate { Interlocked.Increment(ref count); };
// Count for 10 seconds
DateTime start = DateTime.Now;
timer.Enabled = true;
while (DateTime.Now < start + TimeSpan.FromSeconds(10))
Thread.Sleep(10);
timer.Enabled = false;
// Calculate actual frequency
Console.WriteLine(
"Requested frequency: {0}\nActual frequency: {1}\n",
frequency, count / 10d);
}
The output looks like this:
Requested: 5 Hz; actual: 4,8 Hz
Requested: 10 Hz; actual: 9,1 Hz
Requested: 15 Hz; actual: 12,7 Hz
Requested: 20 Hz; actual: 16 Hz
Requested: 30 Hz; actual: 21,3 Hz
Requested: 50 Hz; actual: 31,8 Hz
Requested: 75 Hz; actual: 63,9 Hz
Requested: 100 Hz; actual: 63,8 Hz
Requested: 200 Hz; actual: 63,9 Hz
Requested: 500 Hz; actual: 63,9 Hz
The actual frequency deviates by up to 36% from the requested one. (And evidently cannot exceed 64 Hz.) Given that Microsoft recommends this timer for its "greater accuracy" over System.Windows.Forms.Timer
, this puzzles me.
Btw, these are not random deviations. They are the same values every time.
And a similar test program for the other timer class, System.Threading.Timer
, shows the exact same results.
In my actual program, I need to collect measurements at precisely 50 samples per second. This should not yet require a real-time system. And it is very frustrating to get 32 samples per second instead of 50.
Any ideas?
@Chris:
You are right, the intervals all seem to be integer multiples of something around 1/64th second. Btw, adding a Thread.Sleep(...) in the event handler doesn't make any difference. This makes sense given that System.Threading.Timer
uses the thread pool, so each event is fired on a free thread.
It looks like your actual timer frequencies are 63.9 Hz or integer multiples thereof.
That would imply a timer resolution of about 15 msec (or integer multiples therefof, i.e. 30 msec, 45 msec, etc.).
This, timers based on integer multiples of a 'tick', is to be expected (in DOS for example the 'tick' value was 55 msec / 18 Hz).
I don't know why your tick count is 15.65 mec instead of an even 15 msec. As an experiment, what if you sleep for several msec within the timer handler: might we be seeing 15 msec between ticks, and 0.65 msec in your timer handler at each tick?
Windows (and therefore .NET running on top of it) is a preemptively multitasking operating system. Any given thread can be stopped at any time by another thread, and if the preempting thread doesn't behave properly, you won't get control back when you want it or need it.
That, in a nutshell, is why you cannot be guaranteed to get exact timings, and why Windows and .NET are unsuitable platforms for certain types of software. If lives are in danger because you don't get control EXACTLY when you want it, choose a different platform.
Based on your comments, you shouldn't be using a timer at all. You should be using a loop with a stopwatch to check the interval and a spinlock so you don't lose the quantum.
If you use winmm.dll you can use more CPU time, but have better control.
Here is your example modified to use the winmm.dll timers
And here is the output I get:
Hope this helps.
These classes aren't intended for real-time use and are subject to the dynamic scheduling nature of an operating system like Windows. If you need real-time execution you'd probably want to look at some embedded hardware. I'm not 100% sure but I think .netcpu may be a real-time version of a smaller .NET runtime on a chip.
http://www.arm.com/markets/emerging_applications/armpp/8070.html
Of course - you need to evaluate how important accuracy of those intervals are given that the code attached to them is going to be executing on a non-realtime operating system. Unless of course this is a purely academic question (in which case - yes it is interesting! :P).
Well, I'm getting different number up to 100 Hz actually, with some big deviations, but in most cases closer to the requested number (running XP SP3 with most recent .NET SPs).
The System.Timer.Timer is implemented using System.Threading.Timer, so this explains why you see same results. I suppose that the timer is implemented using some kind of scheduling algorithm etc. (it's internal call, maybe looking at Rotor 2.0 might shed some light on it).
I would suggest to implement a kind of timer using another thread (or combination thereof) calling Sleep and a callback. Not sure about the outcome though.
Otherwise you might take a look at multimedia timers (PInvoke).