什么,如果有的话,是用于使用System.Diagnostics.Stopwatch资源罚? [英] What, if any, is the resource penalty for using System.Diagnostics.Stopwatch?

查看:174
本文介绍了什么,如果有的话,是用于使用System.Diagnostics.Stopwatch资源罚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

  FOO()//一些操作受外部资源。 DB,I / O,等等。
 

VS

 无功表=新的秒表();
watch.Start();
FOO()
VAR时间= watch.ElapsedMilliseconds
watch.Stop();
 

解决方案

我相信秒表是建立在QueryPerformanceCounter的顶部,所以在内核过渡每次通话效果。如果foo()从非常简短,该QPC开销将大大超过它。

如果你使用秒表来测量短的任务,你应该运行FOO()多次(如千),并利用周围的整批秒表。通过运行的次数除以的总时间来获得平均时间的任务。

For example

foo() //Some operation bound by an external resource. db,I/O, whatever.

vs.

var watch = new Stopwatch();
watch.Start();
foo()
var time = watch.ElapsedMilliseconds
watch.Stop();

解决方案

I believe Stopwatch is built on top of QueryPerformanceCounter, so each call results in a kernel transition. If foo() is very brief, the QPC overhead will dwarf it.

If you're using Stopwatch to measure short tasks, you should run foo() many times (like thousands), and use Stopwatch around the whole batch. Divide the total time by the number of runs to get average time for the task.

这篇关于什么,如果有的话,是用于使用System.Diagnostics.Stopwatch资源罚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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