如何衡量 .NET 中的代码性能? [英] How to measure code performance in .NET?

查看:23
本文介绍了如何衡量 .NET 中的代码性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 DateTime 对一行 C# 代码进行真正快速和肮脏的基准测试:

long lStart = DateTime.Now.Ticks;//做点什么long lFinish = DateTime.Now.Ticks;

问题出在结果上:

<前>开始时间 [633679466564559902]完成时间 [633679466564559902]开始时间 [633679466564569917]完成时间 [633679466564569917]开始时间 [633679466564579932]完成时间 [633679466564579932]

...等等.

鉴于开始时间和结束时间相同,Ticks 显然不够细化.

那么,我如何才能更好地衡量绩效?

解决方案

Stopwatch 类从 .NET 2.0 开始可用,是实现此目的的最佳方式.这是一个非常高性能的计数器,精确到几分之一毫秒.看一看 MSDN 文档,这很漂亮清楚.

正如之前所建议的,为了获得合理的平均时间,还建议多次运行您的代码.

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.

这篇关于如何衡量 .NET 中的代码性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆