Click here to Skip to main content
15,867,771 members
Articles / Programming Languages / C#
Article

A High-Precision Stopwatch for C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (22 votes)
17 Jan 2006CPOL1 min read 106K   3K   39   11
This article presents a stopwatch class with microsecond-precision for C# that offers split-time and a System.TimeSpan interface.

Sample Image - CS_Stopwatch.jpg

Introduction

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.

Background

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:

MethodDescription
void Start()Starts the stopwatch.
void Stop()Stops the stopwatch.
void Reset()Resets the stopwatch.
TimeSpan GetElapsedTimeSpan()Returns the elapsed time in the form of a System.TimeSpan.
TimeSpan GetSplitTimeSpan()Returns the split time in the form of a System.TimeSpan.
double GetElapsedTimeInMicroseconds()Returns the elapsed time in microseconds.
double GetSplitTimeInMicroseconds()Returns the split time in microseconds.

An example of how to use this class is given below:

C#
Performance.Stopwatch sw = new Performance.Stopwatch();

sw.Start();

for(int i=0; i<10; i++)
{
   System.Threading.Thread.Sleep(100);
   Console.Write("Split time: ");
   Console.Write(sw.GetSplitTimeInMicroseconds().ToString());
   Console.WriteLine(" microseconds.");
}

sw.Stop();

Console.Write("Total process time: ");
Console.Write(sw.GetElapsedTimeSpan().ToString());
Console.WriteLine(".");

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 Start() and Stop() should result in an elapsed time of 0 +/- 0.500 microseconds.

History

  • 17.Jan.2006 - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Aspen Insights
United States United States
Walter Storm is currently doing quantitative research and data science. Originally from Tunkhannock, PA., he has a B.S. in Aerospace Engineering from Embry-Riddle Aeronautical University[^], and an M.S. in Systems Engineering from SMU[^]. He has been professionally developing software in some form or another since January of 2001.

View Walter Storm's profile on LinkedIn.[^]

Comments and Discussions

 
GeneralMy vote of 5 Pin
iericzhou18-Apr-12 20:01
iericzhou18-Apr-12 20:01 
Questionthis is rather lengthy code Pin
parvez1216-Mar-12 6:04
parvez1216-Mar-12 6:04 
GeneralJust Thanks Pin
Expategghead8-Dec-09 1:30
Expategghead8-Dec-09 1:30 
Generalsamples Pin
kiquenet.com27-Oct-09 22:26
professionalkiquenet.com27-Oct-09 22:26 
Questionthread-safe? Pin
vadivelkumar1-Apr-07 23:22
vadivelkumar1-Apr-07 23:22 
AnswerRe: thread-safe? Pin
Nitron2-Apr-07 2:33
Nitron2-Apr-07 2:33 
General.NET 2.0 Pin
Rei Miyasaka24-Jan-06 9:04
Rei Miyasaka24-Jan-06 9:04 
GeneralSimilar code Pin
Drew Noakes23-Jan-06 23:42
Drew Noakes23-Jan-06 23:42 
GeneralRe: Similar code Pin
Nitron24-Jan-06 2:30
Nitron24-Jan-06 2:30 
General.NET Timing Pin
Marc Clifton17-Jan-06 7:23
mvaMarc Clifton17-Jan-06 7:23 
GeneralRe: .NET Timing Pin
Nitron17-Jan-06 7:45
Nitron17-Jan-06 7:45 
Marc Clifton wrote:
I've found timing things in .NET to be difficult, because the JIT compiler results in a one-time hit.


This was actually one of the things I was trying to measure. Even with JIT, the C# code seems to actually run faster than my C++ code while processing large CSV and other data files. (this was an intresting surprise BTW)

~Nitron.
ññòòïðïðB A
start

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.