Possible Duplicate:
How do I measure how long a function is running?
I have an I/O time-taking method which copies data from a location to another. What's the best and most real way of calculating the execution time? Thread
? Timer
? Stopwatch
? Any other solution? I want the most exact one, and briefest as much as possible.
StopWatch
class looks for your best solution.Also it has a static field called
Stopwatch.IsHighResolution
. Of course, this is a hardware and operating system issue.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:
Example results
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
StopWatch will use the high-resolution counter
If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.
If you are interested in understand performance, the best answer is to use a profiler.
Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.
Stopwatch
is designed for this purpose and is one of the best ways to measure time execution in .NET.Do not use DateTime to measure time execution in .NET.
UPDATE:
As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.