开发者

issue with .NET system.diagnostics stopwatch

开发者 https://www.devze.com 2023-02-07 08:23 出处:网络
i am trying to create an application which incorporates the use of the stopwatch class. Stopwatch sw = new Stopwatch();

i am trying to create an application which incorporates the use of the stopwatch class.

Stopwatch sw = new Stopwatch();
sw.Start();
while (play)
{
    long timer = sw.ElapsedMilliseconds;
    Debug.WriteLine(timer);
}

When i tested this loop and checked the elapsed time, i discovered that the program is missing some milliseconds.

some clockings from the debugger output:

31

32

33

34

35

36

37

38

40 <开发者_StackOverflow社区;------39 missed

41

42

43

Any suggestions on how i can solve this issue?


The miliseconds you're losing is due to the fact that your program isn't the only one running on the OS.

So, once in a while other programs get their time slice, and a few mililseconds are left out.

You can't "fix" it.


Missing milliseconds? Are you expecting to see a entry for every single millisecond tick for a second? E.g. 1000 per second? If so then that will never happen. There is no timing API that is accurate to 1 millisecond.

The fact that you're doing an assignment as well as stream output in the loop where you're outputting the millisecond data in addition to other operating system processes such as task switching means that millisecond accuracy is not possible. You would need a dedicated, real-time machine to pull off the kind of output you're looking for


A Debug.WriteLine can be slower then 1 millisecond. It isn't optimized for speed.

You could add a call placing the message to a list and then write the list to Debug.WriteLine after running. You could add a background task sending the message to Debug.WriteLine.

Both should prevent the timer from missing ticks.

Another reason for missing ticks might be the OS or another program doing some work between two Debug.WriteLine calls. It might even be a slow machine.

Setting the Thread Priority or running this application on a Dedicated machine should help but these kind of timer issues are expected on Windows since it never said it was a Real Time OS.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号