Anthony Gatlin
Anthony Gatlin

Reputation: 4413

How do I create a generic routine to time methods?

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

.NET of course has the Stopwatch class which allows one to easily time a section of code with it's .Start() and .Stop() methods.

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.

Upvotes: 3

Views: 2529

Answers (2)

L.B
L.B

Reputation: 116108

Just a thought. declare a method as below

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

and use as

var duration = Measure(() => MyMethod(param1));

Upvotes: 10

Peter Davidsen
Peter Davidsen

Reputation: 678

You could also look into AOP and dynamically create a wrapper for Timing methods (will only work on non-static public methods though).

If you're using IoC you will basically just need to register the types with a decorator, this can of course be customized and turned on and off if needed, or even on specific methods.

I've used Castle:DynamicProxy before to achieve just this (for both timing and error logging).

Edit: an example (from an old version of castle: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());

Upvotes: 1

Related Questions