How to create a universal procedure for time methods?

I need to measure the execution of many different methods in the context of an application.

.NET, of course, has a Stopwatch class that makes it easy to split a section of code with its .Start () and .Stop () methods.

However, using the Stopwatch class in the usual way requires me to decorate each method with an instance of the stopwatch object and call it .Start () and .Stop ().

I need to use the stopwatch functionality in literally hundreds of methods and I do not want to pollute each method with this code. I would also like to be able to turn the time on and off.

Is there an easy way to implement a universal synchronization solution in my own code? If so, how? Code profilers do this, so I think it should be possible.

+2
source share
2 answers

Just a thought. declare method below

public static long Measure(Action action) { Stopwatch sw = Stopwatch.StartNew(); action(); return sw.ElapsedMilliseconds; } 

and use as

 var duration = Measure(() => MyMethod(param1)); 
+7
source

You can also watch AOP and dynamically create a wrapper for Timing methods (it will only work on non-static public methods).

If you use IoC, you just need to register types with a decorator, this, of course, can be configured and turned on and off, if necessary, or even by certain methods.

I used Castle: DynamicProxy before to achieve just that (for recording time and errors).

Edit: example (from the old version of the lock: dynamic proxy)

 TimerInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { Stopwatch watch = new Stopwatch(); watch.Start(); invocation.Proceed(); watch.Stop(); //here you have the value which could be used to log (which I assume you want) } } new ProxyGenerator().CreateInterfaceProxyWithTarget<IMyInterface>(implementedObject, new TimerInterceptor()); 
0
source

Source: https://habr.com/ru/post/1275261/


All Articles