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

前端 未结 3 1551
梦毁少年i
梦毁少年i 2021-01-14 09:50

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

相关标签:
3条回答
  • 2021-01-14 10:08

    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.

    0 讨论(0)
  • 2021-01-14 10:29

    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 讨论(0)
  • 2021-01-14 10:33

    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.

    0 讨论(0)
提交回复
热议问题