Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I measure the approximation of the time spent in a process context switch?

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.

like image 221
Tito Avatar asked Dec 06 '25 06:12

Tito


1 Answers

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"]);
}
like image 55
sa_ddam213 Avatar answered Dec 07 '25 21:12

sa_ddam213



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!