Best practice for measuring which part of a method is time consuming?

In my initialization method, I call some other methods, manipulate some variables and iterate over some lists. Now I noticed that the boot method takes a little longer (about 2 minutes).

But the problem is that I'm not quite sure which part of the method consumes this a lot of time. Therefore, I would like to measure it so that I can work on this part, which has the highest potential for reducing time.

But what is a good approach to measure this?

+6
optimization c #
source share
3 answers

If you do not want to use a profiler, such as the Ants performance profiler , you can use Stopwatch to determine how long it took to run the code.

 Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // Code to time stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; 

This, of course, changes your code and requires that you make these corrections at every point you want to measure.

I would recommend going with one of the many good profiles out there (I'm sure other answers will point out some good ones).

+10
source share

dotTrace Performance Profiler 4.0 provides line building . This is what you need.

+7
source share

I'm not quite sure which part of the method consumes this a lot of time. So I would like to measure it

Things that take a lot longer than they should be very easy to find .

For example, if it takes 10 times longer than it should, it means that in 90% of cases it does something unnecessary. So, if you run it under the IDE and pause it, the probability that you will catch it in action is 90%. Just look at the call stack because you know that the problem is somewhere on it. If you are not sure you caught him, try several times. The problem will appear on several samples.

Typical things I found in running a .net application:

  • Finding resources like international strings is useless.
  • Tracking notification trees in data structures is unnecessary.

What you find will probably be different, but you will find it.

This is a low-tech but effective method. It works whether the time is wasted in the CPU or in I / O. This does not measure the problem very accurately, but it accurately defines it. (Check out the last paragraph of this post .)

+2
source share

All Articles