我需要衡量应用程序上下文中许多不同方法的执行情况.
I need to measure the execution of many different methods within the context of an application.
.NET当然具有Stopwatch类,该类允许使用.Start()和.Stop()方法轻松地计时一段代码.
.NET of course has the Stopwatch class which allows one to easily time a section of code with it's .Start() and .Stop() methods.
但是,以正常方式使用Stopwatch类需要我用Stopwatch对象的实例装饰每个方法,并调用它的.Start()和.Stop()方法.
However, use of the Stopwatch class in its normal manner requires me to decorate every method with an instance of a Stopwatch object and calls to it's .Start() and .Stop() methods.
我实际上需要在数百种方法上使用秒表功能,并且不想用此代码污染每个方法.我还希望能够打开和关闭计时.
I need to use Stopwatch functionality on literally hundreds of methods and do not want to pollute every method with this code. I would also like to have the ability to turn timing on and off.
有没有一种简单的方法可以在自己的代码中实现通用计时解决方案?如果是这样,怎么办?代码分析器可以做到这一点,所以我认为这是有可能的.
Is there a simple way I can implement a generic timing solution within my own code? If so, how? Code profilers do it, so I think it must be possible.
推荐答案只是一个想法.声明如下方法
Just a thought. declare a method as below
public static long Measure(Action action) { Stopwatch sw = Stopwatch.StartNew(); action(); return sw.ElapsedMilliseconds; }并用作
var duration = Measure(() => MyMethod(param1));更多推荐
如何为方法计时创建通用例程?
发布评论