我写了一个简单的程序,它使用一个计时器来淡出标签。我发现计时器非常不精确,间隔越来越短。
以下代码证明了我的想法:
(我也通过StopWatch实现它。刻度之间的间隔几乎相等。)
private void timer1_Tick(object sender, EventArgs e)
{
elapsed += timer1.Interval;
timerTest.AppendText(DateTime.UtcNow.Second.ToString() + "." + DateTime.UtcNow.Millisecond.ToString() + "\r\n");
if (elapsed >= target)
timer1.Stop();
}
int elapsed = 0;
int target = 4000;
private void button_Click(object sender, EventArgs e)
{
labelFadeout.ForeColor = Color.Greed;
elapsed = 0;
timer1.Interval = 100;
timer1.Tick += timer1_Tick;
timer1.Start();
}
第一个和第五个输出会产生大差异!
[1st] [5th]
20.318 42.955
20.377 42.956
20.491 42.957
20.595 42.958
20.707 42.959
20.814 43.68
20.929 43.69
21.34 43.7
21.142 43.71
21.257 43.72
21.365 43.173
21.471 43.176
21.584 43.177
21.692 43.179
21.8 43.18
21.909 43.286
22.19 43.288
22.127 43.289
22.242 43.291
22.347 43.293
22.454 43.397
22.569 43.4
22.673 43.402
22.784 43.404
22.892 43.406
23.4 43.649
23.112 43.652
23.221 43.655
23.331 43.657
23.494 43.66
23.549 43.746
23.662 43.749
23.779 43.751
23.879 43.754
23.991 43.756
24.95 43.846
24.209 43.848
24.316 43.851
24.427 43.853
24.534 43.855
我已经检查了
并且仍然对如何如此不精确感到好奇。任何人都可以解释这个??
答案 0 :(得分:3)
您的间隔测试方法已关闭。你真的只是在一个时间间隔内获得当前时间的一部分,并期望它与你上一次服用它的时间相当。
如果你想测试一个计时器真正花费多少时间以100个间隔打勾。使用实际的Stopwatch
,并查看它Elapsed
以了解通过了多长时间。
Stopwatch stopwatch = new Stopwatch();
int elapsed = 0;
int target = 4000;
private void timer1_Tick(object sender, EventArgs e)
{
elapsed += timer1.Interval;
timerTest.AppendText(stopwatch.Elapsed.TotalSeconds.ToString());
stopwatch.Restart();
if (elapsed >= target)
timer1.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
elapsed = 0;
timer1.Interval = 100;
timer1.Tick += timer1_Tick;
stopwatch.Start();
timer1.Start();
}
我的结果:
0.1055445
0.0872668
0.1121169
0.1032453
0.1066107
0.1097218
0.103818
0.1079014
...