是否有可能在 C# 中测量进程上下文切换的近似时间? 如果是,如何?
这道题是我根据Cracking the Coding Interview: 150 Programming Questions and Solutions这本书做的.
他们的解决方案是:
假设只有 2 个进程,P1 和 P2。 (是一个巨大的近似值,我相信还有更准确的)
P1 正在执行,P2 正在等待执行。在某些时候,操作系统必须交换 P1 和 P2——假设它发生在 P1 的第 N 条指令处。因此上下文切换时间为:
Time_Stamp(P2_1) - TimeStamp(P2_N)
其中一个问题是我们无法记录进程中每条指令的时间戳。 并且我们不考虑其他进程之间的上下文切换所花费的时间。
最佳答案
你可以使用 WMI (Windows Management Instrumentation)
例子:
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"]);
}
关于c# - 我如何测量在进程上下文切换中花费的时间的近似值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13714822/