Friday, January 30, 2015

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.

No comments:

Post a Comment