Possible Duplicate:
How do I measure how long a function is running?
I have an I/O time-taking method which c
From personal experience, the System.Diagnostics.Stopwatch
class can be used to measure the execution time of a method, however, BEWARE: It is not entirely accurate!
Consider the following example:
Stopwatch sw;
for(int index = 0; index < 10; index++)
{
sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.ElapsedMilliseconds);
}
sw.Stop();
Example results
132ms
4ms
3ms
3ms
2ms
3ms
34ms
2ms
1ms
1ms
Now you're wondering; "well why did it take 132ms the first time, and significantly less the rest of the time?"
The answer is that Stopwatch
does not compensate for "background noise" activity in .NET, such as JITing. Therefore the first time you run your method, .NET JIT's it first. The time it takes to do this is added to the time of the execution. Equally, other factors will also cause the execution time to vary.
What you should really be looking for absolute accuracy is Performance Profiling!
Take a look at the following:
RedGate ANTS Performance Profiler is a commercial product, but produces very accurate results. - Boost the performance of your applications with .NET profiling
Here is a StackOverflow article on profiling: - What Are Some Good .NET Profilers?
I have also written an article on Performance Profiling using Stopwatch that you may want to look at - Performance profiling in .NET