Is there any possibility to measure the approximated time of a process context switch in C#? If yes, how?

I made this question based on the book Cracking the Coding Interview: 150 Programming Questions and Solutions.

Their solution is:

Assume there are only 2 process, P1 and P2. (Is a huge approximation, I believe there are more accurate ones)

P1 is executing and P2 is waiting for execution. At some point OS must swap P1 and P2 - let's assume it happens at the Nth instruction of P1. So the context switch time for this would be:

Time_Stamp(P2_1) - TimeStamp(P2_N)

One of the problems is that we cannot record the timeStamp of every instruction in the process. And we don't consider the spending time of the context switch between other processes.

有帮助吗?

解决方案

You could use WMI (Windows Management Instrumentation)

Example:

ManagementScope managementScope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Thread");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, objectQuery);
ManagementObjectCollection objectCollection = searcher.Get();

foreach (ManagementObject m in objectCollection)
{
    Console.WriteLine("ContextSwitchesPersec : {0}", m["ContextSwitchesPersec"]);
}

其他提示

Process context switching is done by the OS and has nothing to do with .NET or C#.

You can monitor the amount of context switches per second using the Windows Performance Monitor, but the process itself is unaware of any context switches.

You can also use Process Explorer to monitor context switches and the delta for individual processes, these aren't shown by default but can be added from the View, Select Columns, Performance Tab

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top