첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
다운로드

▶ Program.cs

using System;
using System.Threading;

namespace TestProject
{
    /// <summary>
    /// 프로그램
    /// </summary>
    class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        private static void Main()
        {
            Console.Title = "PerformanceCounter 클래스 사용하기";

            WriteLog("카운터 생성을 시작한다.");

            PerformanceHelper helper = new PerformanceHelper();

            WriteLog("카운터 생성을 종료한다.");

            for(int i = 0; i < 10; i++)
            {
                Console.WriteLine();

                WriteLog("CPU 사용률        : {0}", helper.GetCPURate()   );
                WriteLog("메모리 사용률     : {0}", helper.GetMemoryRate());
                WriteLog("디스크 I/O 사용률 : {0}", helper.GetDiskIORate());

                Thread.Sleep(500);
            }
        }

        #endregion
        #region 로그 작성하기 - WriteLog(format, parameterArray)

        /// <summary>
        /// 로그 작성하기
        /// </summary>
        /// <param name="format">포맷 문자열</param>
        /// <param name="parameterArray">매개 변수 배열</param>
        private static void WriteLog(string format, params object[] parameterArray)
        {
            string message;

            if(parameterArray.Length == 0)
            {
                message = format;
            }
            else
            {
                message = string.Format(format, parameterArray);
            }

            string log = string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), message);

            Console.WriteLine(log);
        }

        #endregion
    }
}

 

728x90

 

▶ PerformanceHelper.cs

using System;
using System.Linq;
using System.Diagnostics;
using System.Management;

namespace TestProject
{
    /// <summary>
    /// 성능 헬퍼
    /// </summary>
    public class PerformanceHelper
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// CPU 카운터
        /// </summary>
        private PerformanceCounter cpuCounter;

        /// <summary>
        /// 메모리 카운터
        /// </summary>
        private PerformanceCounter memoryCounter;

        /// <summary>
        /// 디스크 I/O 카운터
        /// </summary>
        private PerformanceCounter diskIOCounter;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - PerformanceHelper()

        /// <summary>
        /// 생성자
        /// </summary>
        public PerformanceHelper()
        {
            this.cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);

            this.memoryCounter = new PerformanceCounter("Memory", "Available KBytes", true);

            string drive = AppDomain.CurrentDomain.BaseDirectory.Substring(0, 2).ToUpper();

            string[] instanceNameArray = new PerformanceCounterCategory("PhysicalDisk").GetInstanceNames();

            string instanceName = instanceNameArray.FirstOrDefault(s => s.IndexOf(drive) > -1);

            this.diskIOCounter = new PerformanceCounter("PhysicalDisk", "% Idle Time", instanceName, true);
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region CPU 사용률 구하기 - GetCPURate()

        /// <summary>
        /// CPU 사용률 구하기
        /// </summary>
        /// <returns>CPU 사용률</returns>
        public float GetCPURate()
        {
            float rate = this.cpuCounter.NextValue();

            rate = Math.Min(100f, Math.Max(0f, rate));

            return rate;
        }

        #endregion
        #region 메모리 사용률 구하기 - GetMemoryRate()

        /// <summary>
        /// 메모리 사용률 구하기
        /// </summary>
        /// <returns>메모리 사용률</returns>
        public float GetMemoryRate()
        {
            using(ManagementClass mc = new ManagementClass("Win32_OperatingSystem"))
            {
                using(ManagementObject o = mc.GetInstances().Cast<ManagementObject>().FirstOrDefault())
                {
                    float physicalMemorySize = float.Parse(o["TotalVisibleMemorySize"].ToString());

                    float rate = ((physicalMemorySize - this.memoryCounter.NextValue()) / physicalMemorySize) * 100;

                    rate = Math.Min(100f, Math.Max(0f, rate));

                    return rate;
                }
            }
        }

        #endregion
        #region 디스크 I/O 사용률 구하기 - GetDiskIORate()

        /// <summary>
        /// 디스크 I/O 사용률 구하기
        /// </summary>
        /// <returns>디스크 I/O 사용률</returns>
        public float GetDiskIORate()
        {
            float rate = 100 - this.diskIOCounter.NextValue();

            rate = Math.Min(100f, Math.Max(0f, rate));

            return rate;
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요