[C#] 전체 메모리 사용량 얻어오기

BruteForceA·2022년 9월 28일
1
using System;
using System.Diagnostics;
using System.Threading;
using System.Management;

namespace ConsoleApp1
{

    class Program
    {
    
        static void Main(string[] args)
        {

            while (true)
            {

             GetTotalUsedMemory();


                int milliseconds = 10000;
                Thread.Sleep(milliseconds);

            }
        }

        public static void GetTotalUsedMemory()
        {
            ManagementClass cls = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection instances = cls.GetInstances();

            foreach (ManagementObject info in instances)
            {
                double total_physical_memeory = double.Parse(info["TotalVisibleMemorySize"].ToString());
                double free_physical_memeory = double.Parse(info["FreePhysicalMemory"].ToString());
                double remain_physical_memory = total_physical_memeory - free_physical_memeory;
                double remain_physical_memory_MB = (total_physical_memeory - free_physical_memeory)/1024;

                Console.WriteLine("Memory Information ================================");

                Console.WriteLine("Total Physical Memory :{0:#.###} GB", total_physical_memeory/ (1024 * 1024));
                Console.WriteLine("Total Physical Memory :{0:#,###} MB", total_physical_memeory/1024);
                Console.WriteLine("Total Physical Memory :{0:#,###} KB", total_physical_memeory);

                Console.WriteLine("Free Physical Memory :{0:#,###} GB", free_physical_memeory/(1024 * 1024));
                Console.WriteLine("Free Physical Memory :{0:#,###} MB", free_physical_memeory/1024);
                Console.WriteLine("Free Physical Memory :{0:#,###} KB", free_physical_memeory);

                Console.WriteLine("Remain Physical Memory : {0:0.00} GB", remain_physical_memory / (1024 * 1024));
                Console.WriteLine("Remain Physical Memory : {0:#,###} MB", remain_physical_memory / 1024);
                Console.WriteLine("Remain Physical Memory : {0:#,###} KB", remain_physical_memory);

                Console.WriteLine("Memory Usage Percent = {0} %", 100 *(int) remain_physical_memory / (int)total_physical_memeory);

                Console.WriteLine();
            }

        }


    }

}

0개의 댓글