本文介绍了如何准确的是Thread.sleep代码(时间跨度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了间歇性失败的单元测试,因为经过的时间是不是我所期望的那样。

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 2999But 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代码(时间跨度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:58
查看更多