This article presents the
Performance.Stopwatch class. This class provides a stopwatch-like behavior using kernel32.dll's
QueryPerformanceCounter. It offers split time and elapsed time with microsecond precision, and also provides a formatted
System.TimeSpan for longer operations. This class is essentially a no-frills stopwatch for measuring the performance of your code.
So I've decided to venture into the world of C#, and needed to see for myself how my application's performance measures up against my C++ code. In order to compare proverbial "apples-to-apples", I needed a high-resolution "stopwatch" to time my code. After some poking around, I saw some alternative ways to do this, however I decided to write my own in order to address the shortcomings of others.
Using the code
The class offers the following public methods:
|Starts the stopwatch.|
|Stops the stopwatch.|
|Resets the stopwatch.|
|Returns the elapsed time in the form of a |
|Returns the split time in the form of a |
|Returns the elapsed time in microseconds.|
|Returns the split time in microseconds.|
An example of how to use this class is given below:
Performance.Stopwatch sw = new Performance.Stopwatch();
for(int i=0; i<10; i++)
Console.Write("Split time: ");
Console.Write("Total process time: ");
This code produces the following output:
Split time: 101403.390654399 microseconds.
Split time: 202629.105095759 microseconds.
Split time: 302948.000374349 microseconds.
Split time: 403266.616287824 microseconds.
Split time: 503606.184584912 microseconds.
Split time: 603955.251295905 microseconds.
Split time: 704231.124346809 microseconds.
Split time: 804552.254546318 microseconds.
Split time: 904863.327601692 microseconds.
Split time: 1005186.13399189 microseconds.
Total process time: 00:00:01.0050000.
Points of Interest
The primary benefit of this class over others is that it provides the user with a
System.TimeSpan interface. This makes it easy to display formatted status information or to calculate how long an operation will take to complete. The class also has a built-in calibration such that a sequential call to
Stop() should result in an elapsed time of 0 +/- 0.500 microseconds.
- 17.Jan.2006 - Initial release.