ALLINSIGHT

Home of the AlmostImplementedException

An easy way to measure a functions performance

At some point in the development of a function or application we ask our self: “Is this the best way to do it”. This is the moment for StopWatch to step forward and help us out.

Normaly we would add StopWatch to the method we want to measure and remove the code afterwards. But that’s alot of work, especialy if want to measure several methods or continuously in a products lifecycle.

But, as promised, there is an easy way to do it. The answer to our prayers is the Action-Delegate. If we use a Delegate as a parameter, we can give a reference of our methode to another one.
This little snippet allows us to measure a methods performance without changing the method itself. We create an Action which is getting another Action as parameter. The actual code to measure is defined as Lamba-Expression

This little snippet allows us to measure a methods performance without changing the method itself. We create an Action which is getting another Action as parameter. The actual code to measure is defined as Lamba-Expression

To use this Action-Delegate we just need to call its name “measure” with the method as parameter

Copy both blocks in a Main-Method and watch the result.

If you want to use “measure” in multiple functions, you can move the first Code-Block over the Main-Method and declare it static. Here is a little example how to do it.

As you can see, I use 2 ways to call measure. The first give a method as parameter, the other one uses Lamba-Expression to produce an anonymous method. Both do the same and you will get round about the same execution time.

Conclusion

There is an easy way to measure the execution time, even from UnitTests without touching the source code. It is also possible to move this methode to an external class, like Tools.cs and declare it as “public static ‘. This way you can use it in any class or project you need it.

As you may have noticed, with the measure-method we just can execute methods or functions without parameters. For this we need to change the inner Action-Declaration and add all the parameters: e.g.

to add an int as parameter.

Share :

Comments are currently closed.