我怎样才能获得在C#中每个内核的CPU负载? [英] How can I get CPU load per core in C#?

查看:184
本文介绍了我怎样才能获得在C#中每个内核的CPU负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到每个核心(四核CPU)CPU负载,在C#中?

How can I get CPU Load per core (quadcore cpu), in C#?

感谢:)

推荐答案

您可以使用WMI或System.Diagnostics命名空间。从那里,你可以抓住任何你想要的性能计数器(但它需要一秒钟(1-1.5s)来初始化那些 - 读值是确定的,唯一的初始化速度慢)

You can either use WMI or the System.Diagnostics namespace. From there you can grab any of the performance counters you wish (however it takes a second (1-1.5s) to initialize those - reading values is ok, only initialization is slow)

code可以关注一下然后是这样的:

Code can look then like this:

    using System.Diagnostics;

    public static Double Calculate(CounterSample oldSample, CounterSample newSample)
    {
        double difference = newSample.RawValue - oldSample.RawValue;
        double timeInterval = newSample.TimeStamp100nSec - oldSample.TimeStamp100nSec;
        if (timeInterval != 0) return 100*(1 - (difference/timeInterval));
        return 0;
    }

    static void Main()
    {
        var pc = new PerformanceCounter("Processor Information", "% Processor Time");
        var cat = new PerformanceCounterCategory("Processor Information");
        var instances = cat.GetInstanceNames();
        var cs = new Dictionary<string, CounterSample>();

        foreach (var s in instances)
        { 
            pc.InstanceName = s;
            cs.Add(s, pc.NextSample());
        }

        while (true)
        {
            foreach (var s in instances)
            {
                pc.InstanceName = s;
                Console.WriteLine("{0} - {1:f}", s, Calculate(cs[s], pc.NextSample()));
                cs[s] = pc.NextSample();
            }
            System.Threading.Thread.Sleep(500);
        }
    }

重要的是,你不能依赖于本地.NET计算100nsInverse性能计数器(仅适用于0或100对我的回报...错误?),但你必须自己进行计算,并为需要最后CounterSamples的存档每个实例(实例重新present核心或这些核心的总和)。

Important thing is that you cant rely on native .net calculation for 100nsInverse performance counters (returns only 0 or 100 for me ... bug?) but you have to calculate it yourself and for that you need an archive of last CounterSamples for each instance (instances represent a core or a sum of those cores).

有似乎是这些实例的命名convetion:

There appears to be a naming convetion for those instances :

0,0 - 第一CPU核心第一
0,1 - 第一CPU第二个核心
0,_Total - 第一个CPU的总负荷
_Total - 所有CPU的总负载

0,0 - first cpu first core 0,1 - first cpu second core 0,_Total - total load of first cpu _Total - total load of all cpus

(未验证 - 不建议依赖它,直​​到进一步的调查做)......

(not verified - would not recommend to rely on it untill further investigation is done)...

这篇关于我怎样才能获得在C#中每个内核的CPU负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆