Using the Stopwatch Class in C#

The .NET Stopwatch class provides a easy mechanism for measuring code execution time. The stopwatch object uses the highest-resolution timing mechanism which the OS and hardware provides, which is normally less than a microsecond. By way of contrast Environment.TickCount and DateTime.Now have a resolution of approximately 15 microseconds.

To use the Stopwatch, simply instantiate a Stopwatch object and then call the StartNew method which starts the timer ticking. A shorter form shown below is just to combine both the instantiation with the start method. The Elapsed property of the object will return the elapsed interval as a TimeSpan:

Stopwatch sObj = Stopwatch.StartNew();
System.IO.File.WriteAllText ("timertest.txt", new string ('*', 30000000));
Console.WriteLine (sObj .Elapsed); // 00:00:01.4322661

In addition, stopwatch also exposes the ElapsedTicks property, that returns the elapsed “ticks” as a long. To convert from ticks to seconds you can simply divide by StopWatch.Frequency. Finally there is also the ElapsedMilliseconds property.
Calling the Stop method halts both the Elapsed and ElapsedTicks although this is not necessary since there is no background activity incurred by a “running” Stopwatch.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

2 Responses to “Using the Stopwatch Class in C#”

  1. Thanks. I didn’t know about the StartNew method. One less line of code to type!

Trackbacks/Pingbacks

  1. Using the .NET Stopwatch class to Profile Your Code | C# Help – C# Tutorials and Resources - February 15, 2011

    [...] Stopwatch class in the System.Diagnostics namespace can be used a as a basic tool to profile blocks of .NET [...]