.NET System.Diagnostics.Stopwatch issue (returns values too low)

前端 未结 7 1265
眼角桃花
眼角桃花 2021-02-13 23:14

On my computer the Stopwatch is returning values way too low. For example, 200 ms when I specified Thread.Sleep(1000). The program is supposed to wait 1 second. I a

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 23:50

    Have a look at the following links:

    https://connect.microsoft.com/VisualStudio/feedback/details/94083/stopwatch-returns-negative-elapsed-time

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

    It seems there is an issue with Stopwatch accuracy which can lead to it returning negative Elapsed times, and also wildly varying times. If you look at the Connect issue, most of the people there are talking about seeing the issue on a virtual machine, which is where we are seeing the negative Elapsed values issue.

    Looking at the QueryPerformanceCounter doc, it seems to imply this issue can happen on multiprocessor systems due to BIOS or hardware abstraction layer bugs, but gives no further information and is not specific about virtualised machines.

    As for the solution to this problem... I haven't found one in a lot of googling. You can ignore values less than zero, which is not ideal but workable in some cases. But that doesn't solve your problem - how do you know what values are invalid?

    Hope this helps somewhat.

提交回复
热议问题