C #에서 CPU 사용량을 얻는 방법?
C #에서 응용 프로그램의 전체 CPU 사용량을 얻고 싶습니다. 프로세스의 속성을 파헤치는 여러 가지 방법을 찾았지만 프로세스의 CPU 사용량과 TaskManager에서 얻는 것과 같은 총 CPU 만 원합니다.
어떻게합니까?
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";
}
필요한 것보다 조금 더 많았지 만 여분의 타이머 코드를 사용하여 1 분 이상의 지속 시간 동안 CPU 사용량이 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";
}
}
꽤 복잡해 보였던 몇 가지 다른 스레드를 읽는 데 시간을 보낸 후 이것을 생각해 냈습니다. SQL Server를 모니터링하려는 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);
}
}
It seems to correctly measure the % of CPU being used by SQL on my 8 core server.
It's OK, I got it! Thanks for your help!
Here is the code to do it:
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;
}
You can use WMI to get CPU percentage information. You can even log into a remote computer if you have the correct permissions. Look at http://www.csharphelp.com/archives2/archive334.html to get an idea of what you can accomplish.
Also helpful might be the MSDN reference for the Win32_Process namespace.
See also a CodeProject example How To: (Almost) Everything In WMI via C#.
CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.
This seems to work for me, an example for waiting until the processor reaches a certain percentage
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();
}
I did not like having to add in the 1 second stall to all of the PerformanceCounter
solutions. Instead I chose to use a WMI
solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a PerformanceCounter
. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.
I started with the snippet from here Returning CPU usage in WMI using C# and added a full explanation of the solution on my blog post below:
Get CPU Usage Across All Cores In C# Using WMI
This class automatically polls the counter every 1 seconds and is also thread safe:
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;
}
}
참고URL : https://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
'Programing' 카테고리의 다른 글
파이썬 코드에서 쉘 스크립트를 호출하는 방법은 무엇입니까? (0) | 2020.05.15 |
---|---|
파이썬에서 [] 연산자를 재정의하는 방법은 무엇입니까? (0) | 2020.05.14 |
Swift는 respondsToSelector에 해당하는 것은 무엇입니까? (0) | 2020.05.14 |
플렉스베이스와 너비의 차이점은 무엇입니까? (0) | 2020.05.14 |
엔터티 프레임 워크 : 하나의 데이터베이스, 여러 DbContext. (0) | 2020.05.14 |