StopWatch vs Timer - When to Use

user4835507 picture user4835507 · Jul 8, 2015 · Viewed 10.9k times · Source

Forgive me for this question, but I can't seem to find a good source of when to use which. Would be happy if you can explain it in simple terms.

Furthermore, I am facing this dilemma:

See, I am coding a simple application. I want it to show the elapsed time (hh:mm:ss format or something). But also, to be able to "speed up" or "slow down" its time intervals (i.e. speed up so that a minute in real time equals an hour in the app).

For example, in Youtube videos (* let's not consider the fact that we can jump to specific parts of the vid *), we see the actual time spent in watching that video on the bottom left corner of the screen, but through navigating in the options menu, we are able to speed the video up or down.

Youtube (2015) video player control bar

And we can actually see that the time gets updated in a manner that agrees with the speed factor (like, if you choose twice the speed, the timer below gets updated twice faster than normal), and you can change this speed rate whenever you want.

enter image description here

This is what I'm kinda after. Something like how Youtube videos measure the time elapsed and the fact that they can change the time intervals. So, which of the two do you think I should choose? Timer or StopWatch?

I'm just coding a Windows Form Application, by the way. I'm simulating something and I want the user to be able to speed up whenever he or she wishes to. Simple as this may be, I wish to implement a proper approach.

Answer

Fabjan picture Fabjan · Jul 8, 2015

As far as I know the main differences are:

Timer

  1. Timer is just a simple scheduler that runs some operation/method once in a while
  2. It executes method in a separate thread. This prevents blocking of the main thread

Timer is good when we need to execute some task in certain time interval without blocking anything.

Stopwatch

  1. Stopwatch by default runs on the same thread
  2. It counts time and returns TimeSpan struct that can be useful in case when we need some additional information

Stopwatch is good when we need to watch the time and get some additional information about how much elapsed processor ticks does the method take etc.