如何为方法计时创建通用例程?

编程入门 行业动态 更新时间:2024-10-27 04:30:37
本文介绍了如何为方法计时创建通用例程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

如何为方法计时创建通用例程?

本文发布于:2023-11-04 00:37:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   例程   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!