如何为方法计时创建通用例程? [英] How do I create a generic routine to time methods?

查看:38
本文介绍了如何为方法计时创建通用例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要衡量应用程序上下文中许多不同方法的执行情况.

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));

这篇关于如何为方法计时创建通用例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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