Thread.Sleep(TimeSpan) 有多准确? [英] How accurate is Thread.Sleep(TimeSpan)?

查看:25
本文介绍了Thread.Sleep(TimeSpan) 有多准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个单元测试间歇性失败,因为所用的时间不是我期望的那样.

I've come across a unit test that is failing intermittently because the time elapsed isn't what I expect it to be.

这个测试的一个例子是:

An example of what this test looks like is:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();

TimeSpan oneSecond = new TimeSpan(0, 0, 1);

for(int i=0; i<3; i++)
{
    Thread.Sleep(oneSecond);
}

stopwatch.Stop();

Assert.GreaterOrEqual(stopwatch.ElapsedMilliseconds, 2999);

大多数时候这都过去了,但至少有一次失败了,因为:

Most of the time this passes but it has failed on at least on one occasion failed because:

预期:大于或等于 2999但是是:2998

Expected: greater than or equal to 2999 But was: 2998

我不明白怎么可能不到 3 秒.Thread.Sleep 或我不知道的秒表是否存在准确性问题?

I don't understand how it could possibly be less than 3 seconds. Is there an accuracy issue with Thread.Sleep or maybe Stopwatch that I'm not aware of?

就像对以下一些问题的更新一样.正在进行单元测试的场景是一个类,它允许调用一个方法来执行某些操作,如果它失败,请等待一秒钟并调用该方法.上面显示的测试只是对所发生情况的近似.

Just as an update to some of the questions below. The scenario that is being unit tested is a class that allow's one to call a method to perform some action and if it fails wait a second and recall that method. The test shown above is just an approximation of what is happening.

假设我想调用一个方法 DoSomething()...但是在 DoSomething() 抛出异常的情况下,我希望能够重试最多调用它 3 次但等待 1 秒每一次尝试.在这种情况下,单元测试的目的是验证当我们请求 3 次重试且每次重试之间等待 1 秒时,所花费的总时间是否大于 3 秒.

Say I wanted to call a method DoSomething()...but in the event of an exception being thrown by DoSomething() I want to be able to retry calling it up to a maximum of 3 times but wait 1 second between each attempt. The aim of the unit test, in this case, is to verify that when we requested 3 retries with 1 second waits between each retry that the total time taken is greater than 3 seconds.

推荐答案

您的线程正在与其他线程共享 CPU 时间.一旦轮到你,睡眠就会结束,内核注意到睡眠时间已经过去,所以它不是那么准确.

Your thread is sharing CPU Time with other threads. The Sleep will end as soon as it is your turn again and the kernel notices the sleep time has elapsed, so it is not that accurate.

CPU 负载、进程优先级、并发线程数,甚至来自其他进程的线程数都会对其产生影响.

CPU load, process priorities, number of concurrent threads, even from other processes, will have effect upon it.

这篇关于Thread.Sleep(TimeSpan) 有多准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆