Understanding StopWatch Class in c#

Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Startmethod, then eventually call the Stop method, and then you check elapsed time using the Elapsed property. (From MSDN)

Let say i want to find out Total Time a Process has been Running. 
1. How many Minutes or Second it took to insert 1000 record in Database?
2. How many time it took to update the Database ? etc ..

I provide a very Basic Example with a Console Application ..

The Stopwatch Class has two Primary Methods 1. Start() 2. Stop() and One Property that is Elapsed .

The Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExample
class Program
static void Main(string[] args)
Stopwatch sw = new Stopwatch();
Console.WriteLine("Stop Watch Start....n");
for (int i = 1; i <= 5; i++)
Console.WriteLine(i + "n");
Console.WriteLine("Stop Watch Stopped:");
Console.WriteLine("Total Time: {0}", sw.Elapsed);

As You can See I have started our Stopwatch Just Before My loop has started.
Now the Loop will Do its work ..
After That As Soon As we are out sw.Stop has been Called.

I have Just Recorded The Timing The Loop Took To Complete.

The Output Will Look SomeThing Like These:


Leave a Reply

Your email address will not be published. Required fields are marked *