tags:

views:

466

answers:

1

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)

+9  A: 

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);
Michael Haren
It seems that the only way to reproduce it is to use a virtual machine. I've tried the code on several desktop machines - no success
Vadmyst
This work-around only eliminates negative values - it does not eliminate the extremely high (false) positive values it also returns.
Will Hughes