Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 秒表:测量时间并在无竞速条件下立即重新启动_C#_.net_Multithreading - Fatal编程技术网

C# 秒表:测量时间并在无竞速条件下立即重新启动

C# 秒表:测量时间并在无竞速条件下立即重新启动,c#,.net,multithreading,C#,.net,Multithreading,我有一个关于.net framework中Stopwatch类的问题。我想测量循环迭代所花费的时间(游戏中的计时) 我担心在测量和重启之间可能会发生上下文切换,并且会损失一些“时间”。 有人知道用原子方式测量和重新启动计时器的方法吗 编辑:不带秒表的解决方案也受欢迎您无需重新启动计时器。您只需记住变量中已用时间的最后一次测量值,然后始终获取差值。类似于(您还必须处理第一次迭代): 但是,为什么您关心在测量已用时间和重新启动计时器之间经过了一段时间?您是否只对“在这里做一些工作”部分感兴趣,还是同

我有一个关于.net framework中Stopwatch类的问题。我想测量循环迭代所花费的时间(游戏中的计时)

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


编辑:不带秒表的解决方案也受欢迎

您无需重新启动计时器。您只需记住变量中已用时间的最后一次测量值,然后始终获取差值。类似于(您还必须处理第一次迭代):

但是,为什么您关心在测量已用时间和重新启动计时器之间经过了一段时间?您是否只对“在这里做一些工作”部分感兴趣,还是同时对“在时间跨度内做一些事情”部分感兴趣


很抱歉格式化,当我在一台真正的计算机上时,我会修复它。

将timer.start放在while循环上方,timer.stop bellow并创建timespan变量=timer.Ellapsed,如果它要记录while循环时间。我不想测量整个while循环,只想测量每次迭代。这是用于一个游戏循环,可能“上下文切换时间”不在其中并不重要。只是我希望它尽可能精确。试想一下:如果我的线程是低优先级的,而一个高优先级的线程启动了,而我的低优先级线程在2分钟内没有cpu周期,或者什么的(刚刚编好:)。这会对测量产生很大影响。我刚刚也想到了这个解决方案。我想做的是模拟一个计时器。我将每个迭代的时间添加到另一个时间跨度中,当这个时间跨度超过某个阈值时,就会触发一个方法。在我的例子中,这是一个具有固定时间步长的gameloop,可以在不同的时间间隔触发更新和绘制。虽然这当然是可行的,但再也没有理由让一个
秒表
实例在内部执行减法了。只需执行
lastTimestamp=Stopwatch.GetTimestamp()
newTimestamp=Stopwatch.GetTimestamp();timespan=timespan.FromTicks(newTimestamp-lastTimestamp);lastTimestamp=newTimestamp
消除了对首次创建秒表对象时的时间戳进行不必要的重复减法。
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
}
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
}
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
}