Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One Timer vs Three Timers Performance

Tags:

c#

.net

timer

I have a question about the usage of System.Timers.Timer in my .NET applications.

I have three different events, one triggers every second, another triggers every minute and the last one triggers every half hour.

Is it better, performance wise, to have one timer or three?

The way to do it with one timer is to check ElapsedEventArgs' SignalTime and compare it to a previously measured time. Of course this doesn't quite work if you've changed the DateTime, but that's not the issue here. Basically every second it elapses I check whether a minute or a half hour has passed as well...

My concern is that using 3 timers creates too much overhead. Am I wrong and should I use 3 for simplicity and clarity or is 1 timer enough?

Code:

private void TimerEverySecondElapsed(object sender, ElapsedEventArgs e)
    {
        timerEverySecond.Enabled = false;
        OnTimerElapsed(TimerType.EverySecond);

        // Raise an event every minute
        if ((e.SignalTime - previousMinute) >= minuteSpan)
        {
            OnTimerElapsed(TimerType.EveryMinute);
            previousMinute = e.SignalTime;
        }

        // Raise an event every half hour
        if ((e.SignalTime - previousHalfhour) >= semiHourSpan)
        {
            OnTimerElapsed(TimerType.EverySemiHour);
            previousHalfhour = e.SignalTime;
        }

        timerEverySecond.Enabled = true;
    }

minuteSpan and semiHourSpan are readonly TimeSpans.

like image 493
Davio Avatar asked Dec 06 '12 11:12

Davio


1 Answers

It's not going to make much of a difference either way. Regardless of the number of timers there's only one loop going on in the background. At it's least efficient you will be using 3 threads from the thread pool but there are a lot available so it's not a big deal. If it makes your code simpler to read I'd say go for it.

Keep in mind however this only applies to Threading.Timer (AKA Timers.Timer). Forms.Timer behaves a bit differently and it would probably would be better to just stick with one of those since it only operates on the UI thread so you may run into some sync issues.

Threading.Timer vs. Forms.Timer

Some More Resources:

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/f9a1c67d-8579-4baa-9952-20b3c0daf38a/

How many System.Timers.Timer instances can I create? How far can I scale?

like image 150
Spencer Ruport Avatar answered Sep 25 '22 07:09

Spencer Ruport