Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Diagnostics.Stopwatch returns negative numbers in Elapsed... properties

Tags:

Is it normal behaviour that Stopwatch can return negative values? Code sample below can be used to reproduce it.

 while (true)         {             Stopwatch sw = new Stopwatch();             sw.Start();             sw.Stop();              if (sw.ElapsedMilliseconds < 0)                 Debugger.Break();          } 

The only place where I can reproduce negative numbers is my virtual machine (hosted by Hyper-V on a 8-core machine)

like image 344
Vadym Stetsiak Avatar asked Jun 17 '09 17:06

Vadym Stetsiak


People also ask

What is elapsed time in stopwatch?

By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value.


1 Answers

This is a bug. It doesn't seem to have a lot of attention around it, through, so I'd suggesting following up with that report.

The uninspiring workaround appears to be to ignore negative values:

long elapsedMilliseconds = Math.Max(0, stopwatch.ElapsedMilliseconds); 
like image 51
Michael Haren Avatar answered Oct 07 '22 18:10

Michael Haren