Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a system clock adjust affect running the stopwatch in C#?

Let's say I have Stopwatch running in my code and in the middle, some other application has changed the system clock (I have Domain Time on my server syncing every second).

Will it affect the stopwatch result?

like image 875
Boppity Bop Avatar asked Dec 29 '12 07:12

Boppity Bop


People also ask

Does stopwatch affect performance?

The Stopwatch isn't doing anything between the calls to Start and Stop ... It just stores the current timestamp (via QueryPerformanceCounter ) when you start it, and compare it to the current timestamp when you stop it. So there is no reason it could affect the performance of your code, at least not significantly.

Why is stopwatch not accurate?

Timing with a stopwatch has quite a large uncertainty (accuracy error) due to the problem of actually having to press the button at the right time to start and stop it. Human reaction time can be as much as 2or 3 tenths of a second.


2 Answers

It depends.

Stopwatch relies on Win32 QueryPerformanceCounter() only if it is available. This implementation is timechange tolerant.

In case high-resolution counters are not available, Stopwatch falls back to system timer, basically DateTime.UtcNow.Ticks call. In this unfortunate case Stopwatch results will be affected by time(not timezone) changes.

As it is written in cited MSDN article, you can check if high-resolution counters are available using IsHighResolution field.

You can blame .Net team using this won't fix defect :)

like image 90
Shaedar Avatar answered Oct 20 '22 00:10

Shaedar


No, internally Stopwatch relies on Win32 QueryPerformanceCounter() which is not tied to the system clock.

like image 34
Inisheer Avatar answered Oct 20 '22 01:10

Inisheer