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
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.
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.
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.