如何衡量.NET code性能?性能、NET、code

2023-09-02 21:24:28 作者:幻

我正在做一些真正的快速和肮脏的基准对C#code。使用的DateTime一行:

 长lStart = DateTime.Now.Ticks;
// 做一点事
长lFinish = DateTime.Now.Ticks;
 

现在的问题是在:

开始时间[633679466564559902]
完成时间[633679466564559902]

开始时间[633679466564569917]
完成时间[633679466564569917]

开始时间[633679466564579932]
完成时间[633679466564579932]

...等等。

由于开始和结束的时间是相同的,蜱显然是不够精细。

所以,我怎么能更好地衡量性能?

解决方案

秒表类,可用自.NET 2.0,是去是最好的方法。这是一个非常高的性能计数器精确到毫秒级。 看看在 MSDN文档,这是pretty的清晰。

编辑:作为previously建议,最好也运行,以获得合理的平均时间的时候你的codeA号

微软推出AI服务 Code Optimizations,帮开发者改进.NET应用性能

I'm doing some real quick and dirty benchmarking on a single line of C# code using DateTime:

long lStart = DateTime.Now.Ticks;
// do something
long lFinish = DateTime.Now.Ticks;

The problem is in the results:

Start Time [633679466564559902]
Finish Time [633679466564559902]

Start Time [633679466564569917]
Finish Time [633679466564569917]

Start Time [633679466564579932]
Finish Time [633679466564579932]

...and so on.

Given that the start and finish times are identical, Ticks is obviously not granular enough.

So, how can I better measure performance?

解决方案

The Stopwatch class, available since .NET 2.0, is the best way to go for this. It is a very high performance counter accurate to fractions of a millisecond. Take a look at the MSDN documentation, which is pretty clear.

EDIT: As previously suggested, it is also advisable to run your code a number of times in order to get a reasonable average time.

 
精彩推荐
图片推荐