views:

366

answers:

5

I would like to be able to calculate the amount of time a number of functions take to execute. I was thinking about using some type of stopwatch class. I can call start/stop before and after each function call, however that seems horribly ugly to me. Is there a way to do this without a stopwatch class? Can something in the Reflections class help with this?

Thanks in advance for you input.

+2  A: 

I recommend the sponsor of the performance tag ... Red Gate Ants. You can get a demo that will run your app and give you performance information for every line and every method that your app hits while it is being profiled.

Jake Pearson
A: 

There are various timers. System.Timers.Timer would be one such. But as the previous answer suggests, are you sure this is the right solutio to the problem you're actually trying to address?

David M
No, I'm not sure. I have a few ideas, but very open to suggestions. Thanks!
J.Hendrix
+1  A: 

i think you should think about using code profiling... Use an external application like Ants Profiler to profile your code? Ants is from Red Gate and not free but i think that there are a some free/open source apps out there as well.

Some free/open source profilers here...

It's ok to stopwatch a method here and there but trying to do that for every method in your solution would quickly become unwieldy.

Paul Sasik
I will take a look at Ants. My thought was to be able to turn it on and off using some sort of flag. I want to be able to run it in a production environment to help trouble shoot network, SQL, or other IO bottle-necks.
J.Hendrix
+1  A: 

you could put the stopwatch class into an attribute used to decorate your methods, i.e. the AOP style. check out this

Joachim Kerschbaumer
+1 Nice! I think this is what I am looking for. I have never decorated a method before. Will this work in 2.0? Do I need to add any references to the project?
J.Hendrix
+3  A: 

I think u must try the PostSharp way http://www.postsharp.org/

Changing the code in the sample for this one:

public class ProfileMethodsAttribute : OnMethodBoundaryAspect 
{ 
  public override void OnEntry( MethodExecutionEventArgs eventArgs) 
  { eventArgs.MethodExecutionTag = Stopwatch.StartNew();  } 

  public override void OnExit( MethodExecutionEventArgs eventArgs) 
  { 
     // Here u can get the time
     Console.WriteLine(((Stopwatch)eventArgs.MethodExecutionTag).ElapsedMilliseconds);
  } 
}

You can get the time off any method

MarcosMeli
+1 This looks good so far.
J.Hendrix