0

Possible Duplicate:
Wrapping StopWatch timing with a delegate or lambda?

Hi,

Each time I want to check elapsed time for given method I have to do :

StopWatch sw = new StopWatch()
sw.Start();
MyMethod();
sw.Stop();

var result = sw.Elapsed.TotalMiliseconds;

It's not comfortable, I would like to have method like:

result = CheckTimeElapsed(MyMethod);

How to write method CheckTimeElapsed?

I don't know how to declare such delegate which may have any number of arguments.

For example function which I want to measue may have argument int

result = CheckTimeElapsed(MySecondMethod(10));

Thanks for help

Community
  • 1
  • 1
gruber
  • 26,743
  • 31
  • 120
  • 211
  • Your first example, `CheckTimeElapsed(MyMethod);`, treats `MyMethod` as a first-class function (which you can't directly do in C#). This is different from your second example, `CheckTimeElapsed(MySecondMethod(10));`, where you pass the value _returned_ by `MySecondMethod(10)`. Which do you want? – Matt Ball Dec 15 '10 at 01:08
  • Fact That May Interest Only Me: First time I've noticed a question on SO where the first three interactions were from three different people named 'Matt'. – Matt Davis Dec 15 '10 at 01:13
  • I want to pass in any way Method which I would like to be executed (possibly this method takes arguments) – gruber Dec 15 '10 at 01:13
  • @Matt: what's really going to bake your noodle later on is, would you still have broken it if I hadn't said anything? _...hold on a sec_ – Matt Ball Dec 15 '10 at 01:17
  • @Matt Ball: You can treat methods as first-class objects in C# via delegates. The syntax he has provided will compile just fine if `CheckTimeElapsed()` takes an `Action` as its first argument, and MyMethod takes no arguments. – cdhowie Dec 15 '10 at 01:22
  • @cdhowie: thanks for the correction/clarification - you can probably guess, but I'm no C-pound programmer. – Matt Ball Dec 15 '10 at 01:35

0 Answers0