views:

477

answers:

3

Dear all

I have a multithreaded C# program where I need to log how many ticks each thread spends in a specific spin wait lock.

I know there are methods for doing that from C or assembler, but is it possible from to access the same counter directly from C# in some way, that is, without going through the Stopwatch class (I assume calling Start/Stop on that has some overhead, and I am not sure how precise it is)?

Thanks, Egil.

+4  A: 

You could use QueryPerformanceCounter and QueryPerformenceFrequency.
You can find an example here.

System.Diagnostics.Stopwatch should be a high-perfomance counter.
However, it it not present in Compact Framework but the above solution fixes that problem.

Sani Huttunen
+6  A: 

Before you "rule out" using System.Diagnostics.Stopwatch : does your test system support high-resolution stopwatch ? : see MSDN on 'StopWatch : check-out : 'Frequency and 'IsHighResolution.

Excellent SO thread on getting the "best" out of StopWatch : SO thread don't miss comments by Eric Lippert

Precision vs. accuracy in .net time measurement : SO thread : Precision vs. accuracy in .NET time measurement may be helpful.

"Cost" of API calls in C# to Win32 APIs : QueryPerformanceFrequency and QueryPerformanceCounter : compared to StopWatch ?

One API example from C# here on Codeproject : 2006 code, author in a comment says he did not consider thread safety

Other threads here on SO have dealt with issues like compensating for the one-time JIT hit of managed code ("dry run" warm-up technique), forcing Garbage Collection, and Finalizers, etc. Easy to find.

BillW
+1  A: 

Look into StopWatch class which is based upon QueryPerformance* APIs is precisely for this purpose.

MSDN:

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

Also results collected by Kristof Verbiest is worth a glipse.

KMan