1

Possible Duplicate:
Profiling a method in C# to know how long does it take to run

I need to check how long does it take to run a method.

For example, I need to know how long does it take to run GetTypes() method in using System.Reflection in my project.

foreach (Type t2 in a.GetTypes())
{
    Console.WriteLine(t2);
}

The easiest way might be running profiler or insert Stopwatch all the source files that uses GetTypes(), but I hope I could use hooking the GetTypes() method to start and quit the stop watch before and after running GetTypes() method.

sw = Stopwatch.StartNew();
foreach (Type t2 in a.GetTypes())
{
    Console.WriteLine(t2);
}
sw.Stop();

Can I do that with C#/.NET(Mono)? If not, do I have other options than modifying the source code or running the profiler?

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • @Michael Petito : I intentionally made two questions, this question is about hooking method to profile something (you can see the comment 'or (not) running the profiler' to specify this, the other question is about using profiler to do the same thing. – prosseek Jun 05 '11 at 18:06
  • @Michael Petito : Profiler might be the best way to go, however I have some more action to be done, in this case I need to modify the code. – prosseek Jun 05 '11 at 18:10

1 Answers1

1

With your example:

sw = Stopwatch.StartNew();
foreach (Type t2 in a.GetTypes())
{
    Console.WriteLine(t2);
}
sw.Stop();

you are measuring much more than GetTypes, you are measuring Console.WriteLine and everything else as well.

Writing a hook (like Moles) would probably influence the performance too much (however I must admit that I have never done something like that before, but I do notice the difference in performance when running unit tests that have Moles).

The easiest option (and cheapest) is to download one of these (free) profilers:

AQTime (free version) http://smartbear.com/products/free-tools/aqtime-standard/

SharpDevelop (has a profiler): http://www.icsharpcode.net/opensource/sd/download/

XTE Profiler http://www.xteprofiler.com

Any of these will give you detailed information. But if you really want to do it yourself, download the source of SharpDevelop and try to figure out how they made the profiler.

Louis Somers
  • 2,560
  • 3
  • 27
  • 57