简体   繁体   English

C#秒表计时异步/等待方法不准确

[英]C# Stopwatch to time an async/await method inaccurate

I'm writing some performance tests, and want to be able to time a method that is asynchronous. 我正在写一些性能测试,并希望能够为异步的方法计时。 The code looks like this, where action is a Func<Task<HttpResponseMessage>> : 代码如下所示,其中actionFunc<Task<HttpResponseMessage>>

var sw = new Stopwatch();
HttpResponseMessage response = null;

sw.Start();
response = await action().ConfigureAwait(continueOnCapturedContext: false);
sw.Stop();

The code compiles and runs ok, but the measured milliseconds are about 100 times higher than the request timings we see in Fiddler - Fiddler reports 200-300ms, but the stop watch reports ~30,000ms. 代码编译并运行正常,但测量的毫秒数比我们在Fiddler中看到的请求时间高约100倍 - Fiddler报告200-300ms,但秒表报告~30,000ms。 Is there some catch about timing asynchronous methods? 有关定时异步方法的问题吗? Is the solution to do the timing in the action itself (which would be annoying?) 解决方案是在动作本身进行计时(这会很烦人吗?)

This should work fine for measuring the true amount of time it takes for your asynchronous task to finish. 这应该可以很好地衡量异步任务完成所需的时间。 You need to keep in mind that: 你需要记住:

  1. the time you are measuring with Fiddler is measuring the request only, and none of the time it takes for your code to process the response. 您使用Fiddler进行测量的时间仅用于测量请求,而且您的代码无需处理响应。
  2. there is a significant difference in time here and you should easily be able to time your code yourself to see how long it takes to progress from a break point before your request to after your request. 这里的时间存在显着差异,您应该可以轻松地自己计算代码,以查看从请求之前的断点到请求之后需要多长时间。 If this is closer to 30 seconds then your stop watch is probably accurate. 如果这接近30秒,那么你的秒表可能是准确的。
  3. there isn't anything obvious to me that would make your time inaccurate. 对我来说没有什么可以让你的时间不准确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM