秒表:测量时间并在没有竞争条件的情况下立即重启

时间:2013-06-19 03:06:29

标签: c# .net multithreading

我对.net框架中的Stopwatch类有疑问。我想测量循环迭代所花费的时间(游戏中的时间)

Stopwatch timer = new Stopwatch();
timer.Start(); // Edited this in, forgot about that
while(true)
{
    var timespan = timer.Elapsed;
    timer.Restart();
    // do something with the timespan

    // Do some work here
}

我担心在测量和重启之间可能会发生上下文切换,并且会丢失一些“时间”。 有没有人知道以原子方式测量和重启计时器的方法?

编辑:欢迎没有秒表的解决方案

2 个答案:

答案 0 :(得分:0)

您不必重新启动计时器。你可以记住变量中Elapsed的最后一次测量,然后总是取差。类似的东西(你还必须处理第一次迭代):

Stopwatch timer = new Stopwatch();
var lastElapsed = timer.Elapsed;
while(true)
{
    var newLastElapsed = timer.Elapsed;
    var timespan = newLastElapsed - lastElapsed;
    lastElapsed = newLastElapsed;
    // do something with the timespan

    // Do some work here
}

但是,为什么要注意在测量Elapsed和重新启动计时器之间经过了一段时间?您是否只想测量“在这里做一些工作”部分还是测量“用时间跨度做某事”部分?

答案 1 :(得分:0)

Stopwatch timer = new Stopwatch();
timer.Start();
var previous = timer.elapsed;
while(!done)
{
    var current = timer.Elapsed;
    var elapsed = current - previous;
    previous = current;
    // use elapsed
    // do the rest of your work
}

很抱歉格式化,我正在使用真正的计算机时修复它。