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

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

彩扇题诗 发布于 2021-11-29 字数 255 浏览 725 回复 3 原文

For example

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


var watch = new Stopwatch();
var time = watch.ElapsedMilliseconds

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


你与昨日 2022-06-07 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.)

凉栀 2022-06-07 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?

战皆罪 2022-06-07 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.