.NET Using Stopwatch class to measure execution time for code

By Indranil Chatterjee

StopWatch provides a convinient way to measure the time of executon of a code segment. This FAQ explains some simple usages of that class.

There are times when we need to measure the time (duration) of execution of a code segment or a method, especially when we are writing multithreaded apps. Traditionally, developers have resorted to the following pattern:

var startTime = DateTime.Now;
//Execute the code fragment
var endTime = DateTime.Now; //Then they calculate the difference between start and end times.

With the Stopwatch class, this is much easier and it requires lesser code and variables to manage.

//Start a stopwatch:
var watch = Stopwatch.StartNew(); //This code initializs a new Stopwatch, sets its elapsed time property to zero and starts measuring elapsed time.
//Execute the code
watch.Stop(); //This stops the watch
The elapsed time can be measured by using Elapsed, ElapsedMilliSeconds and ElapsedTicks properties.
A call to watch.Reset() stops time interval measurement and resets elapsed time to zero.
watch.ReStart() is similar to Reset() except that it also starts a fresh recording of elapsed time.

This is a method that can be used to profile/record the execution time of any method:

private long RecordTime(Action method)
{
var timer = Stopwatch.StartNew();
method();
timer.Stop();

return timer.ElapsedMilliseconds;
}

This takes in an Action delegate (so that one can pass any method call wrapped in a delegate) and it executes the passed delegate to record ite elapsed execution time and returns the elapsed time in milliseconds.

.NET Using Stopwatch class to measure execution time for code  (1547 Views)