开发者

Is it possible to read the internal CPU tick counter from C#?

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 fro开发者_如何学编程m 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜