.NET provides plenty of ways for delaying the execution using timers. But many programmers keep thinking of getting a way out to know the time required to execute a code in the application. How do we do this?
The conventional way to do this is to do something like the following snippet:
- int startTime = System.DateTime.Now.Millisecond;
-
- int stopTime = System.DateTime.Now.Millisecond;
- int difference = stopTime - startTime;
But fortunately, .NET provides the Stopwatch Class, in the namespace System.Diagnostics that allows us to accurately measure elapsed time in a software application. This is cleaner and reliable. A Stopwatch instance can measure elapsed time over several intervals with the total elapsed time calculated by adding all of the intervals together.
The difference in time is available as a TimeSpan and is formatted as d.hh:mm:ss.ff:
- d = days
- hh = hours
- mm = minutes
- ss = seconds
- ff = fractions of a second
The following is an example of using StopWatch Class to get the time elapsed instead of the above method.
- using System.Diagnostics;
-
- Stopwatch stopWatchObj = new Stopwatch();
- stopWatchObj.Start();
-
- stopWatch.Stop();
- TimeSpan ts = stopWatch.Elapsed;
I hope this blog helps in understanding the most convenient way to get the time required to execute a code snippet and helps in making more reliable applications.
Happy Coding.