如何获得超过2个内核的CPU使用率?

spy*_*chu 7 c# performancecounter cpu-usage

我尝试将我的程序CPU使用量除以核心.现在我使用PerformanceCounter并在0到1之间更改InstanceName我有来自2个核心的数据.

PerformanceCounter pc0 = new PerformanceCounter("Processor", "% Processor Time", "0");
PerformanceCounter pc1 = new PerformanceCounter("Processor", "% Processor Time", "1");
Run Code Online (Sandbox Code Playgroud)

如何获得第3,第4核等的核心使用?

有人能帮帮我吗?

谢谢

RB.*_*RB. 9

我怀疑你真正问的是" 我如何计算核心数量?".此代码将计算核心数,然后基于此创建性能计数器.

        int coreCount = 0;
        foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
        {
            coreCount += int.Parse(item["NumberOfCores"].ToString());
        }

        PerformanceCounter[] pc = new PerformanceCounter[coreCount];

        for (int i = 0; i < coreCount; i++)
        {
            pc[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
            Console.WriteLine(pc[i].CounterName);
        }
Run Code Online (Sandbox Code Playgroud)


Eam*_*voy 5

我之前没有使用过PerformanceCounter,但这样做有什么问题吗?

PerformanceCounter pc0 = new PerformanceCounter("Processor", "% Processor Time", "0");
PerformanceCounter pc1 = new PerformanceCounter("Processor", "% Processor Time", "1");
PerformanceCounter pc2 = new PerformanceCounter("Processor", "% Processor Time", "2");
PerformanceCounter pc3 = new PerformanceCounter("Processor", "% Processor Time", "3");
Run Code Online (Sandbox Code Playgroud)


小智 5

这可能是一个古老的问题,但是对于其他寻求不同解决方案的人,为什么不使用System.Environment?

    public static List<System.Diagnostics.PerformanceCounter> GetPerformanceCounters()
    {
        List<System.Diagnostics.PerformanceCounter> performanceCounters = new List<System.Diagnostics.PerformanceCounter>();
        int procCount = System.Environment.ProcessorCount;
        for (int i = 0; i < procCount; i++)
        {
            System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", i.ToString());
            performanceCounters.Add(pc);
        }
        return performanceCounters;
    }
Run Code Online (Sandbox Code Playgroud)

编辑:我注意到这仅返回逻辑处理器的数量,而不是实际的核心数量。