Wednesday, 13 March 2013

Stopwatch in c#

Stopwatch measures time elapsed. It is useful for micro-benchmarks in code optimization. It can perform routine and continuous performance monitoring. The Stopwatch type, found in System.Diagnostics, is useful in many contexts.


Example

First, Stopwatch is a class in the .NET Framework that is ideal for timing any operation in your C# programs. You must create Stopwatch as an instance. This makes it useful in multi-threaded applications or websites.
Program that uses Stopwatch [C#]

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
 // Create new stopwatch
 Stopwatch stopwatch = new Stopwatch();

 // Begin timing
 stopwatch.Start();

 // Do something
 for (int i = 0; i < 1000; i++)
 {
     Thread.Sleep(1);
 }

 // Stop timing
 stopwatch.Stop();

 // Write result
 Console.WriteLine("Time elapsed: {0}",
     stopwatch.Elapsed);
    }
}

Output

Time elapsed: 00:00:01.0001477
Ref:
MSDN : Stopwatch Class 




No comments:

Post a Comment