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