Many a times I had to measure the time a method, a module or a functionality is taking. The only way I knew till now was to do it the DateTime way. Now, there is a new class to help us out with that: Stopwatch
Earlier, I would have to get the current time before start, current time after finish, then use the TimeSpan class to subtract after and before times, to finally get the elapsed time. All this has been made a little easier by the introduction of Stopwatch class.
Stopwatch class is in System.Diagnostics namespace. Lets take a look at the code:
And here is the output:
So, first up we create an instance of Stopwatch class. Then we call simple Start and Stop methods to use the stopwatch. The object has ElapsedMilliseconds and Elapsed properties to measure the elapsed time. You can "Start" or "Restart" the stopwatch anytime. "Start" means stopwatch will start from the same time it was stopped last time. "Restart" will reset the stopwatch to 0, and then start counting the time.

No comments: