【发布时间】:2013-06-19 03:06:28
【问题描述】:
我对 .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
}
我担心在测量和重新启动之间可能会发生上下文切换,并且会丢失一些“时间”。 有谁知道以原子方式测量和重新启动计时器的方法?
编辑:也欢迎没有秒表的解决方案
【问题讨论】:
-
把 timer.start 放在 while 循环之上,timer.stop 放在下面并创建时间跨度变量 = timer.Ellapsed,如果它记录 while 循环时间。
-
我不想测量整个 while 循环,而只想测量每次迭代。这用于游戏循环,其中“上下文切换时间”可能并不重要。只是我想让它尽可能精确。并想一想:如果我的线程是低优先级并且高优先级线程启动并且我的低优先级在 2 分钟内没有 cpu 周期或其他什么(只是弥补:))怎么办。这会对测量产生很大影响。
标签: c# .net multithreading