我想在c#中获得一个应用程序的总的CPU使用情况。我已经找到了很多方法来深入研究进程的属性,但我只想知道进程的CPU使用情况,以及你在TaskManager中得到的总CPU。
我怎么做呢?
我想在c#中获得一个应用程序的总的CPU使用情况。我已经找到了很多方法来深入研究进程的属性,但我只想知道进程的CPU使用情况,以及你在TaskManager中得到的总CPU。
我怎么做呢?
当前回答
对于那些仍然无法获得与任务管理器匹配的CPU使用总数的人,您应该使用以下语句:
new PerformanceCounter("Processor Information", "% Processor Utility", "_Total");
其他回答
您可以使用System.Diagnostics中的PerformanceCounter类。
像这样初始化:
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";
}
比要求的多一点,但我使用额外的计时器代码来跟踪和警报,如果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 = (int)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";
}
}
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/
这个类每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;
}
}
CMS是正确的,但如果你使用visual studio中的服务器资源管理器,并摆弄性能计数器选项卡,那么你就可以找到如何获得许多有用的指标。