Mahdi Tahsildari Mahdi Tahsildari - 10 months ago 54
C# Question

Calculate the execution time of a method

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?
? Any other solution? I want the most exact one, and briefest as much as possible.

Answer Source

Stopwatch is designed for this purpose and is one of the best way to measure time execution in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTimes to measure time execution in .NET.


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.