[c#] 프로세스의 cpu 점유율 측정하기 – PerformanceCounter
private void button1_Click(object sender, EventArgs e)
{
PerformanceCounter performanceCounter = new("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
label1.Text = performanceCounter.NextValue().ToString("0.00");
performanceCounter.Dispose();
}
To read from a performance counter, create an instance of the PerformanceCounter class, set the CategoryName, CounterName, and, optionally, the InstanceName or MachineName properties, and then call the NextValue method to take a performance counter reading.
– PerformanceCounter Class
CategoryName과 CounterName을 아규먼트로 넣어야 하는데 InstanceName 등은 넣어야 할 때가 있고 그러지 않아도 될 때가 있다는 말이다. 특정 프로세스의 cpu 점유율을 확인할 때에는 InstanceName까지 설정해야 한다.
그리고 카운터를 읽을 때에는 NextValue 메떠드를 호출하라는 설명이다. 이름이 그냥 Value가 아니고 CurrentValue도 아닌 건 저 메떠드를 호출한 때 이미 구해진 값을 그냥 가져오는 게 아니라 호출을 해야 그때부터 값을 구하기 때문이다. 값을 구하는 데에 일정한 시간이 필요한 거도 있다.
CategoryName과 CounterName은 윈도우즈 성능 모니터를 보면 된다. 리소스 모니터와 헷갈리지 않도록 유의하는 게 좋다. 성능 모니터는 perfmon.msc /s로 실행되고 리소스 모니터는 perfmon.exe /res로 실행이 된다. 따라서 윈도우즈의 서치 바에서 그냥 perfmon이라고 쳐서 찾으면 엉뚱하게 리소스 모니터를 실행하게 될 수도 있다.
성능 모니터 > 모니터링 도구 > 성능 모니터 > +
위와 같이 하면 CategoryName과 CounterName이 많이 나오는데 이들 가운데 필요한 걸 찾으면 된다.
프로세스는 객체다. 여러 프로세스들은 프로세스 객체의 인스턴스들이다. Process.GetCurrentProcess().ProcessName은 PerformanceCounter의 인스턴스가 만들어진 프로세스의 인스턴스 이름을 반환한다.
When you have finished using the type, you should dispose of it either directly or indirectly.
– ibid.
PerformanceCounter를 다 쓴 뒤에는 dispose해야 한다는 말이다.