How to determine the number of context switches that occurred when running C # code?

From C # can I determine the number of context switches that occurred while executing a block of code in a particular thread? Ideally, I would like to know how many times and which processor was specified in my stream code.

I know that I can use tools such as Event Tracing for Windows and related viewers, but it seemed a little harder to get the data I wanted.

In addition, tools such as Process Explorer are too difficult to determine how many switches occurred as a result of a particular block of code.

Background . I am trying to check the actual performance of a low-level blocking primitive in .NET (as a result of some comments on a recent blog post I made.

+4
source share
3 answers

It looks like procexp can use kernel stream (KTHREAD) or execution stream (ETHREAD) data structures that have a ContextSwitches field on it. Perhaps this can be obtained from managed code.

0
source

It looks like you can look for a software solution, but if not, then Microsoft Process Explorer will tell you very easily the number of context switches for a particular thread.

In the tool, double-click your process, select the Themes tab, and select a thread.

The .NET tab contains more specific .NET-related source data.

+3
source

I have never done this, but here are a few examples that might help:

  • .NET profiler APIs can let you connect? The ICorProfilerCallback interface has callbacks RuntimeThreadSuspended and RuntimeThreadResumed. But the comment on this blog post seems to indicate that they won’t get what you are looking for: "RuntimeThreadSuspended is issued when the thread pauses at run time, usually in preparation for the GC to execute.

  • There is a Context Switches / sec perfmon switch counter that can help. I did not specifically consider this account, but I assume that it works with Win32 threads and is not thread driven. You can use the profiling API to get the Win32 thread id for any given managed thread id.

Good luck!;)

+1
source

Source: https://habr.com/ru/post/1277342/


All Articles