Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]

Stopwatch your code!

Timing managed code is one thing I do quite often. I guess measurement of the method level execution times is a common task for any application developer for that matter. I have used various methods for measurement; the worst of them all is using DateTime. DateTime simply does not give you that high resolution timing. The alterative was to use a couple of Win32 API called QueryPerformanceCounter and QueryPerformanceFrequency. If you have used MS Enterprise Library, you would see that the Microsoft.Practices.EnterpriseLibrary.Logging.Tracing.Tracer class uses these API for timing. There is a small catch in the implementation though. Since P/Invoke is involved here, every call would result in UnManagedCode permission being demanded. The stack walk thus performed results in some loss in the resolution of the timing. Therefore, it is fair enough to mark the native method helpers with the SuppressUnmanagedCodeSecurityAttribute. This attribute ensures that the permission demand happens only at link time (JIT compile time), and not for subsequent calls. If you are well aware of the security implications of this attribute usage, you are ready to go.

 

Okay wait, don’t go far implementing all what I said earlier; System.Diagnostics.Stopwatch in .NET 2.0 gives you just that. Here’s a snippet:

 

Stopwatch watch = new Stopwatch();
watch.Start();
// Some operation
watch.Stop();
int elapsedTime = watch.ElapsedMilliseconds;

 

The best part of about the Stopwatch class is that it intelligently uses a resolution based on whether the underlying hardware supports a high one or not (QueryPerformanceFrequency API returns true if high resolution is supported). If not supported, the Stopwatch reverts to that provided by DateTime. You can query the IsHighResolution static property to find out whether high resolution is supported on your machine.  

 

Posted: Tue, Sep 27 2005 19:46 by Manoj G | with no comments
Filed under:
Leave a Comment

(required) 

(required) 

(optional)

(required)