Wednesday 12 December 2012

C# Stopwatch

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 multithreaded 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

The code includes the "using System.Diagnostics" namespace at the top. This is where the Stopwatch class is defined in the Framework. You can see the Stopwatch is created with the new operator in Main

1 comment: