안녕하세요.
오늘은 C#에서 CPU와 RAM(메모리), 디스크 사용량을 불러오는 방법을 알아보겠습니다.
이 글에서는 .NET 6.0을 기준으로 합니다.
전체 코드는 맨 아래에 있습니다.
먼저 성능을 불러오기 위해 NuGet에서 System.Diagnostics.PerformanceCounter를 설치해주세요.
그리고 코드에서
using System.Diagnostics;
using System.Runtime.InteropServices;
두 가지를 가져와주세요.
그리고 PerformanceCounter를 이용해서 CPU 사용량과
사용 가능한 램 용량과 시스템에 설치된 총 램 용량을 가져옵니다.
( 램 사용량은 사용 가능한 램 용량과 시스템에 설치된 총 램 용량을 이용해서 Main()에서 계산합니다)
private static readonly PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
private static readonly PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
하지만 여기서 바로 cpuCounter를 사용하면 작동이 되지 않습니다.
작동되게 하기 위해서 Main()에서
디스크 사용량과 램 사용률 계산, CPU 사용률 처리를 만들어줘야 합니다.
디스크 사용량부터 시작하겠습니다.
먼저 Main()에서 C 드라이브의 정보를 가져옵니다.
그리고 C 드라이브에 사용 가능한 용량과 총 용량을 가져와서 백분율로 계산해 줍니다.
DriveInfo dInfo = new DriveInfo("C");
string disk = (100 - ((dInfo.AvailableFreeSpace / (float)dInfo.TotalSize) * 100)).ToString("F1");
그러면 디스크는 끝났습니다.
다음으로는 램 사용량을 가져와야 합니다.
먼저 memKb에 시스템 메모리 정보를 담아주고
아까 만든 ramCounter에서 ramCounter.NextValue()로 값을 가져오고
백분율로 계산해 줍니다.
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
string ram = (100 - ((ramCounter.NextValue() / (memKb / 1024)) * 100)).ToString("F1");
이제 램 사용량도 끝났습니다.
마지막으로 CPU 사용량입니다.
아까 만든 cpuCounter에서 cpuCounter.NextValue()로 사용량을 가져오면 되는데
저만 그런 건지는 모르겠지만 처음에는 무조건 0으로 표시가 되어서
처음에는 cpu 사용량을 2번 담아줘야 정상적으로 담깁니다.
이제 CPU 사용량도 완성되었습니다.
string cpu = cpuCounter.NextValue().ToString("F1");
cpu = cpuCounter.NextValue().ToString("F1");
이제 Console에 출력해 보면 정상적으로 값이 표시되는 것을 확인하실 수 있습니다.
Console.WriteLine(cpu);
Console.WriteLine(ram);
Console.WriteLine(disk);
(1번째 줄:CPU / 2번째 줄:RAM / 3번째 줄:디스크)
글 읽어주셔서 감사합니다.
(예시와 전체 코드는 아래에 있습니다)
0.5초마다 사용량을 출력하는 예시:
using System.Diagnostics;
using System.Runtime.InteropServices;
public class Program
{
private static readonly PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
private static readonly PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
static void Main()
{
string cpu = cpuCounter.NextValue().ToString("F1");
while (true)
{
DriveInfo dInfo = new DriveInfo("C");
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
cpu = cpuCounter.NextValue().ToString("F1");
string ram = (100 - ((ramCounter.NextValue() / (memKb / 1024)) * 100)).ToString("F1");
string disk = (100 - ((dInfo.AvailableFreeSpace / (float)dInfo.TotalSize) * 100)).ToString("F1");
Console.Clear();
Console.WriteLine(cpu);
Console.WriteLine(ram);
Console.WriteLine(disk);
Thread.Sleep(500);
}
}
}
더보기를 클릭하시면 예시 코드가 표시됩니다.
전체코드:
using System.Diagnostics;
using System.Runtime.InteropServices;
public class Program
{
private static readonly PerformanceCounter cpuCounter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
private static readonly PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);
static void Main()
{
DriveInfo dInfo = new DriveInfo("C");
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
string cpu = cpuCounter.NextValue().ToString("F1");
cpu = cpuCounter.NextValue().ToString("F1");
string ram = (100 - ((ramCounter.NextValue() / (memKb / 1024)) * 100)).ToString("F1");
string disk = (100 - ((dInfo.AvailableFreeSpace / (float)dInfo.TotalSize) * 100)).ToString("F1");
Console.WriteLine(cpu);
Console.WriteLine(ram);
Console.WriteLine(disk);
}
}
'프로그래밍' 카테고리의 다른 글
[Kotlin] SharedPreferences 데이터 전부 지우기 (0) | 2025.03.23 |
---|---|
초보자도 쉽게 만드는 파이썬 디스코드 봇 (0) | 2025.01.19 |
[Python] module 'httpcore' has no attribute 'NetworkBackend' 해결 방법 (0) | 2023.11.22 |