Timing Managed Code

Note: this entry has moved.

As part of the samples included in my last presentation about .NET Performance and Scalability, there is a useful class that encapsulates the Win32 functions QueryPerformanceCounter and QueryPerformanceFrequency. These functions let you measure the performance of your code to nanosecond accuracy (10-9 sec). However, after all internal and interop cross-boundary calls, you get 10 us (10-6 sec) that is an order of magnitude better that the 10 milliseconds resolution of the managed DateTime class.

 

Note: This class (Stopwatch) resembles (same interface definition) the one in the .NET Framework 2.0 (Whidbey) that you will found on the System.Diagnostics namesapece. The good thing is that you can use this class with .NET Framework v1.1 and you will have full compatibility when v2.0 comes up.

 

 

Downloads

 

You can download the code from here.

 

 

Usage

 

Its usage is very straightforward.

 

Stopwatch myTimer = new Stopwatch();

 

myTimer.Start();

// Do some stuff here

myTimer.Stop();

// Show Results

double result = myTimer.Elapsed.TotalMilliseconds;

Console.WriteLine( "Elapsed milliseconds: {0}", result );

 

// If you want a new timing, just reset the current timer

myTimer.Reset();

 

 

Enjoy it!

Published Friday, June 25, 2004 12:23 PM by HernanDL
Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)