Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 5개 있습니다.)
.NET Framework: 442. C# - 시스템의 CPU 사용량 및 프로세스(EXE)의 CPU 사용량 알아내는 방법
; https://www.sysnet.pe.kr/2/0/1684

Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법
; https://www.sysnet.pe.kr/2/0/13215

Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)
; https://www.sysnet.pe.kr/2/0/13582

Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
; https://www.sysnet.pe.kr/2/0/13583

닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API
; https://www.sysnet.pe.kr/2/0/13589




C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API

우선, "/Process (_Total)/% Processor Time" 성능 카운터를 살펴보면,

using (var total = new PerformanceCounter("Process", "% Processor Time", "_Total", true))
{
    // total.RawValue == 1 Core 기준 1초에 1씩 증가
    // total.NextSample().CounterType == Timer100Ns
}

RawValue는 1 Core 기준으로 ("%" 수치이기 때문에) 초당 1씩 증가하는 누적 수치입니다. 그런데, CounterType이 Timer100Ns인데요, 즉 RawValue는 100ns 단위이기 때문에 1이 아니라 10_000_000씩 증가합니다. 만약, 16 Core 기준이라면 160_000_000씩 증가하게 됩니다.

테스트를 위해 아래의 코드로,

long _oldTotalValue = 0;

private void ProcessCpu(string instanceId)
{
    using (var total = new PerformanceCounter("Process", "% Processor Time", "_Total", true))
    {
        var totalValue = total.RawValue;

        try
        {
            if (_oldTotalValue == 0)
            {
                return 0.0f;
            }

            var diffTotalValue = totalValue - _oldTotalValue;
            Console.WriteLine($"Total: {total.RawValue}, Diff: {diffTotalValue}");
        }
        finally
        {
            _oldTotalValue = totalValue;
        }
    }
}

1초당 실행해 보면 대략 이런 결과가 나옵니다.

// 16 Core 환경에서 실행

Total: 564078281250, Diff: 157656250
Total: 564240312500, Diff: 159843750
Total: 564397812500, Diff: 160000000
Total: 564560156250, Diff: 162187500
Total: 564717500000, Diff: 157500000
Total: 564879218750, Diff: 159687500
...[생략]...

정확히 1초에 한 번씩 구해오는 것은 아니므로 대략 160_000_000 정도가 꾸준히 증가하는 것을 볼 수 있고 이 값을 100ns 기준으로 하면 16, 즉 1600%씩 증가하는 것입니다.

그리고 이 성능 카운터는 같은 범주에 있는 "% Privileged Time"과 "% User Time"의 합입니다.

["/Process (_Total)" 범주]

"/% Processor Time" = "/% Privileged Time" + "/% User Time" 

여기서 "% Privileged Time"은 다시 "Kernel Time"과 "Idle Time"을 합친 값에 해당합니다. 이유는 알 수 없지만 Idle Time에 대한 정보를 성능 카운터에서는 제공하지 않으므로, 이것만으로는 _Total CPU의 Kernel + User 모드 사용량을 구할 수 없습니다. 만약 CPU 사용량을 구하고 싶다면 별도의 "\Processor Information(_Total)" 범주에서 제공하는 성능 카운터를 사용해야 합니다.




"/Process (_Total)/% Processor Time" 성능 카운터를 이해했다면, 이제 "/Process ([프로세스])/% Processor Time" 성능 카운터도 쉽게 이해할 수 있습니다.

이것 역시 Timer100Ns 단위의 값으로 1 Core 기준으로 100%를 사용했다면 "/Process (_Total)/% Processor Time" 값과 일치하게 증가하는 누적값입니다. 따라서 그 2개의 증가 값을 백분율로 환산하면 특정 프로세스의 CPU 사용량을 계산할 수 있습니다.

string instanceId = GetProcessInstanceName(pid);
long _oldTotalValue = 0;
long _oldProcessValue = 0;

private void ProcessCpu(string instanceId)
{
    using (var total = new PerformanceCounter("Process", "% Processor Time", "_Total", true)) // 전체 사용량에 대한 성능 카운터
    using (var process = new PerformanceCounter("Process", "% Processor Time", instanceId, true)) // 프로세스에 대한 성능 카운터
    {
        var totalValue = total.RawValue;
        var processValue = process.RawValue;

        try
        {
            var diffTotalValue = totalValue - _oldTotalValue;
            var diffProcessValue = processValue - _oldProcessValue;

            var cpuUsage = ((float)diffProcessValue / diffTotalValue) * 100.0f;
            Console.WriteLine($"CPU: {cpuUsage}%");
        }
        finally
        {
            _oldTotalValue = totalValue;
            _oldProcessValue = processValue;
        }
    }
}

하지만, 저 코드는 아주 정밀하다고 볼 수는 없습니다. 왜냐하면 RawValue를 구하는 코드는 실행할 때마다 달라질 수 있기 때문에 아래의 2개 라인이,

var totalValue = total.RawValue;
var processValue = process.RawValue;

동시에 실행되지 않는 한 미세하게 차이가 날 수 있습니다. 물론, 그런 오차는 현실적으로 허용 가능한 수준입니다. 그런 의미에서 봤을 때 사실 _Total을 굳이 구할 필요도 없습니다. 어차피 (16 코어의 경우) 대략 1600%씩 증가하는 값이라고 오차 범위를 둘 수 있으므로 간단하게 CPU Core 숫자로 나누는 것과 유사한 효과를 갖게 됩니다. 결국, 위의 코드는 다음과 같이 간략하게 정리가 됩니다.

private void ProcessCpu(string instanceId)
{
    var cpu = new PerformanceCounter("Process", "% Processor Time", instanceId, true); // 프로세스에 대한 성능 카운터
    var rawValue = cpu.RawValue;

    var diffValue = rawValue - _oldProcessValue;
    _oldProcessValue = rawValue;

    var cpuUsage = ((float)diffValue / 100_000f) / Environment.ProcessorCount;
    Console.WriteLine($"CPU: {cpuUsage}%");
}

/* 1초마다 실행 결과:
CPU: 0.1953125%
CPU: 0.390625%
CPU: 0.78125%
CPU: 0.78125%
CPU: 1.7578125%
CPU: 0.48828125%
CPU: 0.09765625%
CPU: 0.9765625%
CPU: 0.1953125%
...[생략]...
*/

(위의 CPU 수치는 작업 관리자의 "Details" 탭에 있는 프로세스 목록의 CPU 칼럼과 유사한 값을 보입니다.)

그리고 PerformanceCounter의 경우 매번 생성할 필요가 없다면 위와 같이 "_old..." 값을 보관해서 사용할 필요 없이 NextValue() 메서드를 곧바로 써도 무방합니다. 게다가, NextValue()가 반환하는 값이 이미 퍼센트(%) 처리까지 돼 있기 때문에 100_000으로 나누는 것도 생략할 수 있습니다.

var cpu = new PerformanceCounter("Process", "% Processor Time", instanceId, true);

while (true)
{
    Thread.Sleep(1000);
    var cpuUsage = cpu.NextValue() / Environment.ProcessorCount;
    Console.WriteLine($"[next] CPU: {cpuUsage}%");
}

간단하죠? ^^




위의 성능 카운터는 별도의 Win32 API로도 제공되는데, 이에 대해서는 지난 글에 한번 설명한 적이 있습니다.

C# - 시스템의 CPU 사용량 및 프로세스(EXE)의 CPU 사용량 알아내는 방법
; https://www.sysnet.pe.kr/2/0/1684

"/Process (_Total)/% Processor Time"에 해당하는 성능 카운터는 GetSystemTimes를 이용해 구할 수 있는데,

[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetSystemTimes(out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);

여기서 lpKernelTime은 lpIdleTime을 포함한 값이기 때문에 실제 수치는 아래와 같이 계산할 수 있습니다.

FILETIME sysIdle, sysKernel, sysUser;
GetSystemTimes(out sysIdle, out sysKernel, out sysUser);

ulong uKernel = FileTimeToLong(sysKernel);
ulong uUser = FileTimeToLong(sysUser);
ulong uIdle = FileTimeToLong(sysIdle);

ulong kernelOnly = uKernel - uIdle;

private ulong FileTimeToLong(FILETIME time)
{
    return ((ulong)time.dwHighDateTime << 32) | (uint)time.dwLowDateTime;
}

[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
    public uint dwLowDateTime;
    public uint dwHighDateTime;
}

그리고 이렇게 구한 값은 이전에 다룬 성능 카운터의 수치와 같습니다.

"/Process (_Total)/% Processor Time" == uKernel + uUser
"/Process (_Total)/% Privileged Time" == uKernel
"/Process (_Total)/% User Time" == uUser

그러니까, 성능 카운터와는 다르게 Idle 값을 구할 수 있으므로 CPU 사용량을 계산하는 것이 가능합니다.

CPU 사용량 = (kernelOnly + uUser) / (uKernel + uUser) * 100

물론, GetSystemTimes는 성능 카운터의 RawValue처럼 누적값을 반환하므로 (대개의 경우 1초마다) 간격을 두고 그 차이 값으로 사용량을 구하는 것이 더 일반적입니다.

CPU 사용량 = (kernelOnlyDiff + uUserDiff) / (uKernelDiff + uUserDiff) * 100




개별 프로세스(Instance)에 대한 성능 카운터, 즉 "/Process ([프로세스])/% Processor Time"도 Win32 API로 제공됩니다.

GetProcessTimes function (processthreadsapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes

BOOL GetProcessTimes(
  [in]  HANDLE     hProcess,
  [out] LPFILETIME lpCreationTime,
  [out] LPFILETIME lpExitTime,
  [out] LPFILETIME lpKernelTime,
  [out] LPFILETIME lpUserTime
);

보는 바와 같이 (lpCreationTime, lpExitTime은 제외하고) Kernel Time과 User Time을 제공합니다. (Idle Time은 실행 프로세스의 경우 의미가 없으므로 out 인자에 없습니다.)

각각 다음과 같이 성능 카운터에 대응하고,

"/Process ([프로세스])/% Processor Time" == lpKernelTime + lpUserTime
"/Process ([프로세스])/% Privileged Time" == lpKernelTime
"/Process ([프로세스])/% User Time" == lpUserTime

이 값은 C#의 Process 타입에서도 동일하게 구할 수 있습니다.

using (Process currentProcess = Process.GetCurrentProcess())
{
    // "/Process ([프로세스])/% Processor Time" == currentProcess.TotalProcessorTime.Ticks
    // "/Process ([프로세스])/% Privileged Time" == currentProcess.PrivilegedProcessorTime.Ticks
    // "/Process ([프로세스])/% User Time" ==  currentProcess.UserProcessorTime.Ticks
}

따라서, (GetSystemTimes를 통해 구한 _Total 값에 의존할 필요 없이) 위의 코드만을 이용해 프로세스 스스로의 CPU 사용률을 구할 수 있습니다.

long _oldTotalValue = 0;

private void ProcessCpu()
{
    using (Process currentProcess = Process.GetCurrentProcess())
    {
        var rawValue = currentProcess.TotalProcessorTime.Ticks;
        var diffValue = rawValue - _oldTotalValue;

        var cpuUsage = ((float)diffValue / 100_000f) / Environment.ProcessorCount;
        Console.WriteLine($"[C#] CPU: {cpuUsage}%");

        _oldTotalValue = rawValue;
    }
}




이번 글에서 설명한 CPU 성능 카운터는 모두 "time-based performance counters"에 속하는 값으로 윈도우의 "작업 관리자" 도구에서 "Details" 탭으로 제공하는 수치에 해당합니다.

반면 "utility performance counters"의 경우, CPU 수준에 대해서는 "\Processor Information\% Processor Utility" 성능 카운터를 이용해 구할 수는 있지만 아쉽게도 "Process" 수준에 대해서는 관련 성능 카운터가 제공되지 않습니다. 그뿐만 아니라 Win32 API로도 제공하지 않는데요, 따라서 "작업 관리자"의 Processes 탭에 있는 CPU 수치를 구할 수 있는 방법이 없습니다.

Process Explorer에서조차도 프로세스의 CPU 사용량은 "time-based performance counters"에 해당하는 값을 보여줍니다. (만약, "utility performance counters"를 보여준다면 그것의 오픈 소스 버전에 해당하는 Process Hacker를 참조해 힌트라도 얻을 수 있을 것 같은데... ^^;)

과연 TaskManager는 (Processes 탭의) 수치를 어떤 방법으로 구해 보여주는 것일까요? ^^ (혹시 아시는 분은 덧글 부탁드립니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 3/29/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11457정성태2/17/201824056.NET Framework: 732. C# - Task.ContinueWith 설명 [1]파일 다운로드1
11456정성태2/17/201829795.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법 [7]파일 다운로드1
11455정성태2/17/201818692오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201827564기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201819526오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201825045기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201819260디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201834546Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201821903오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201819442오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201820765.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201821789.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201819674.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201819756VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201820352VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201818136개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201816651오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201819929.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
11439정성태1/17/201824825기타: 69. C# - CPU 100% 부하 주는 프로그램파일 다운로드1
11438정성태1/17/201819561오류 유형: 446. Error CS0234 The type or namespace name 'ITuple' does not exist in the namespace
11437정성태1/17/201818876VS.NET IDE: 124. Platform Toolset 설정에 따른 Visual C++의 헤더 파일 기본 디렉터리
11436정성태1/16/201821116개발 환경 구성: 352. ASP.NET Core (EXE) 프로세스가 IIS에서 호스팅되는 방법 - ASP.NET Core Module(AspNetCoreModule) [4]
11435정성태1/16/201822204개발 환경 구성: 351. OWIN 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11434정성태1/15/201822583개발 환경 구성: 350. 사용자 정의 웹 서버(EXE)를 IIS에서 호스팅하는 방법 - HttpPlatformHandler (Reverse Proxy)파일 다운로드2
11433정성태1/15/201820684개발 환경 구성: 349. dotnet ef 명령어 사용을 위한 준비
11432정성태1/11/201826420.NET Framework: 726. WPF + Direct2D + SharpDX 출력 C# 예제파일 다운로드2
... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...