What, if any, is the resource penalty for using System.Diagnostics.Stopwatch?

一个人想着一个人 提交于 2019-12-29 06:17:31

问题


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();

回答1:


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.




回答2:


This sounds like a recursive answer but the only way to truly know the penalty of Stopwatch is to measure it. Measuring managed code usually involves Stopwatch instances.

Stopwatch is only meant for diagnostic purposes though and should not be used in a retail application. Unless of course you are in a diagnostic mode. Hence this really shouldn't be an issue for non-diagnostic code. Can you provide some insight into your scenario so that we can give a better answer?

Stopwatch instances are built (usually) on top of a QueryPerformanceCounter call. These are not free but they're not terribly expensive either. Anything that's worth measuring with a Stopwatch will be a long enough running task that the cost of the task will make the QueryPerformanceCounter call insignificant. Otherwise, why are you measuring it?




回答3:


In my experience, there is some noticeable overhead when using the Stopwatch class. Certainly much more than using Environment.TickCount or such to measure time, but still not too great. However, this may or may not be a big problem for you. If the time period being measured is typically a very short one (as should usually be the case when using Stopwatch, given that other methods are just as good for timing longer periods), then performance shouldn't be affected perceptably, I'd imagine. Also, the end of this page has a bit to say about the cost of running a Stopwatch in your program. (Not sure I would take the advice on using it for constant program monitoring however.)



来源:https://stackoverflow.com/questions/795377/what-if-any-is-the-resource-penalty-for-using-system-diagnostics-stopwatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!