Best practice to measure which part of a method takes a lot of time?
In my initialization method I call some other methods, m开发者_C百科anipulate some variables and iterate over some lists. Now I noticed that the loading method takes a little bit long (approximately 2 minutes).
But the problem is, I'm not quite sure which part of the method is consuming this much time. So I'd like to measure it so that I can work on this part that has the highest potential to reduce time.
But what is a good approach to measure that?
If you don't want to use a profiler such as the Ants performance profiler, you can use the Stopwatch
to measure how long it took some code to run.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Code to time
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
This, of course changes your code and requires you to make these amendments in every point you want to measure.
I would recommend going with one of the many good profilers out there (I am certain other answers will point out some good ones).
The dotTrace Performance Profiler 4.0 provides line-by-line profiling. That's what you need.
I'm not quite sure which part of the method is consuming this much time. So I'd like to measure it
Things that take much longer than they should are very easy to find.
For example, if it's taking 10 times longer than it should, that means 90% of the time it is doing something not needed. So, if you run it under the IDE and pause it, the chance you will catch it in the act is 90%. Just look at the call stack, because you know the problem is somewhere on it. If you're not sure you've caught it, try it several times. The problem will appear on multiple samples.
Typical things I've found in .net app startup:
- Looking up resources such as international strings, needlessly.
- Walking notification trees in data structures, to a needless extent.
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 spent in CPU or in I/O. It does not measure the problem very precisely, but it does locate it very precisely. (Check the last paragraph of this post.)
精彩评论