可能的重复:
如何测量函数运行的时间? https://stackoverflow.com/questions/10107140/how-to-measure-how-long-is-a-function-running
我有一个 I/O 计时方法,可以将数据从一个位置复制到另一个位置。计算执行时间的最佳且最真实的方法是什么?Thread
? Timer
? Stopwatch
?还有其他解决方案吗?我想要最准确、尽可能简短的。
Stopwatch https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-8.0是为此目的而设计的,是测量 .NET 中执行时间的最佳方法之一。
var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not使用日期时间 https://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance测量 .NET 中的执行时间。
UPDATE:
正如 @series0ne 在评论部分所指出的:如果您想要真正精确地测量某些代码的执行情况,则必须使用操作系统内置的性能计数器。这以下答案 https://stackoverflow.com/questions/1409762/creating-a-perfmon-counter-to-record-an-average-per-call-c/1409833#1409833包含一个很好的概述。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)