0

我正在尝试创建一个包含秒表类使用的应用程序。

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

当我测试这个循环并检查经过的时间时,我发现程序丢失了几毫秒。

来自调试器输出的一些时钟:

31
32
33
34
35
36
37
38
40 <------39 错过
41
42
43

关于如何解决这个问题的任何建议?

4

3 回答 3

5

您丢失的毫秒数是由于您的程序不是唯一在操作系统上运行的程序。

因此,有时其他程序会得到它们的时间片,而忽略了几毫秒。

你不能“修复”它。

于 2011-01-30T23:01:35.637 回答
5

缺少毫秒?您是否希望看到每毫​​秒滴答一秒钟的条目?例如每秒 1000 次?如果是这样,那将永远不会发生。没有精确到 1 毫秒的计时 API。

除了任务切换等其他操作系统进程之外,您正在输出毫秒数据的循环中进行分配和流输出这一事实意味着毫秒精度是不可能的。您需要一台专用的实时机器来实现您正在寻找的那种输出

于 2011-01-30T23:03:35.773 回答
0

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.

于 2013-06-05T06:44:57.233 回答