如何在C#中获得CPU使用率?

时间:2008-11-10 15:01:40

标签: c# cpu-usage

我想获得C#中应用程序的总CPU使用率。我已经找到了许多方法来深入研究进程的属性,但我只想要进程的CPU使用率,以及你在TaskManager中获得的总CPU。

我该怎么做?

10 个答案:

答案 0 :(得分:186)

您可以使用PerformanceCounter中的System.Diagnostics课程。

像这样初始化:

PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");

这样消费:

public string getCurrentCpuUsage(){
            return cpuCounter.NextValue()+"%";
}

public string getAvailableRAM(){
            return ramCounter.NextValue()+"MB";
} 

答案 1 :(得分:52)

比请求的要多一点,但我使用额外的计时器代码来跟踪并警告CPU使用率是否持续1分钟或更长时间内是否为90%或更高。

public class Form1
{

    int totalHits = 0;

    public object getCPUCounter()
    {

        PerformanceCounter cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

                     // will always start at 0
        dynamic firstValue = cpuCounter.NextValue();
        System.Threading.Thread.Sleep(1000);
                    // now matches task manager reading
        dynamic secondValue = cpuCounter.NextValue();

        return secondValue;

    }


    private void Timer1_Tick(Object sender, EventArgs e)
    {
        int cpuPercent = getCPUCounter();
        if (cpuPercent >= 90)
        {
            totalHits = totalHits + 1;
            if (totalHits == 60)
            {
                Interaction.MsgBox("ALERT 90% usage for 1 minute");
                totalHits = 0;
            }                        
        }
        else
        {
            totalHits = 0;
        }
        Label1.Text = cpuPercent + " % CPU";
        Label2.Text = getRAMCounter() + " RAM Free";
        Label3.Text = totalHits + " seconds over 20% usage";
    }
}

答案 2 :(得分:19)

花了一些时间阅读几个看起来相当复杂的不同线程,我想出了这个。我需要它用于我想监视SQL服务器的8核机器。对于下面的代码,我将“sqlservr”作为appName传递。

private static void RunTest(string appName)
{
    bool done = false;
    PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
    PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
    while (!done)
    {
        float t = total_cpu.NextValue();
        float p = process_cpu.NextValue();
        Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
        System.Threading.Thread.Sleep(1000);
    }
}

它似乎正确地衡量了我的8核服务器上SQL使用的CPU百分比。

答案 3 :(得分:14)

没关系,我明白了!谢谢你的帮助!

以下是执行此操作的代码:

private void button1_Click(object sender, EventArgs e)
{
    selectedServer = "JS000943";
    listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}

private static int GetProcessorIdleTime(string selectedServer)
{
    try
    {
        var searcher = new
           ManagementObjectSearcher
             (@"\\"+ selectedServer +@"\root\CIMV2",
              "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");

        ManagementObjectCollection collection = searcher.Get();
        ManagementObject queryObj = collection.Cast<ManagementObject>().First();

        return Convert.ToInt32(queryObj["PercentIdleTime"]);
    }
    catch (ManagementException e)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }
    return -1;
}

答案 4 :(得分:9)

您可以使用WMI获取CPU百分比信息。如果您具有正确的权限,甚至可以登录到远程计算机。查看http://www.csharphelp.com/archives2/archive334.html以了解您可以完成的任务。

同样有用的可能是Win32_Process命名空间的MSDN参考。

另请参阅CodeProject示例How To: (Almost) Everything In WMI via C#

答案 5 :(得分:5)

CMS是正确的,但如果您在visual studio中使用服务器资源管理器并使用性能计数器选项卡,那么您可以弄清楚如何获得许多有用的指标。​​

答案 6 :(得分:3)

这似乎对我有用,等待处理器达到一定百分比的例子

var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
int usage = (int) cpuCounter.NextValue();
while (usage == 0 || usage > 80)
{
     Thread.Sleep(250);
     usage = (int)cpuCounter.NextValue();
}

答案 7 :(得分:2)

我不喜欢在所有PerformanceCounter解决方案中添加1秒钟。相反,我选择使用WMI解决方案。存在1秒等待/停顿的原因是为了在使用PerformanceCounter时读数准确。但是,如果你经常调用这种方法并刷新这些信息,我建议不要经常发生这种延迟......即使考虑做一个异步过程来获得它。

我从这里开始使用代码段Returning CPU usage in WMI using C#,并在我的博客文章中添加了解决方案的完整说明:

Get CPU Usage Across All Cores In C# Using WMI

答案 8 :(得分:1)

此类每1秒自动轮询一次计数器,并且也是线程安全的:

public class ProcessorUsage
{
    const float sampleFrequencyMillis = 1000;

    protected object syncLock = new object();
    protected PerformanceCounter counter;
    protected float lastSample;
    protected DateTime lastSampleTime;

    /// <summary>
    /// 
    /// </summary>
    public ProcessorUsage()
    {
        this.counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public float GetCurrentValue()
    {
        if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
        {
            lock (syncLock)
            {
                if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)
                {
                    lastSample = counter.NextValue();
                    lastSampleTime = DateTime.UtcNow;
                }
            }
        }

        return lastSample;
    }
}

答案 9 :(得分:0)

public int GetCpuUsage()
{
    var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", Environment.MachineName);
    cpuCounter.NextValue();
    System.Threading.Thread.Sleep(1000); //This avoid that answer always 0
    return (int)cpuCounter.NextValue();
}

此链接https://gavindraper.com/2011/03/01/retrieving-accurate-cpu-usage-in-c/中的原始信息

相关问题