본문 바로가기
프로그래밍/C++

[C++] 현재 프로세스의 CPU 사용율(점유율) 구하기

by 건우아빠유리남편 2021. 1. 6.
반응형

현재 제공되는 프로그램이 PC 내의 CPU를 모두 점유하면 안되는 상황에서 해당 프로세스가 너무 오래 점유 하면 잠시 Delay를 주어 처리할 수 있을 것 같아요.

Thread의 우선순위를 변경하여 어느정도 CPU 점유율을 낮출 수도 있을 것 같아요.

아래 관련된 Stuff 코드를 참고 해보세요 ㅎㅎ

#pragma once
/**
 * @brief CPU 사용율 디버깅을 위한 클래스.
 * 현재 프로세스가 쓰고 있는 CPU를 반환한다.
*/
class CPUChecker
{
public:
    static CPUChecker* instance()
    {
        static CPUChecker conf_;
        return &conf_;
    }
    virtual ~CPUChecker(void);

    /**
     * @brief 현재 프로세스가 쓰고 있는 CPU 사용률을 로그파일 및 디버그뷰에 출력한다.
    */
    void PrintCPUUsage()
    {
        TCHAR szMsg[256] = { 0, };
        _tsprintf(szMsg, 256, _T("Current CPU Usage : %.2f"), dVal);
        TRACE(szMsg);

        // 지정된 사용범위를 넘어서면 위험 로그를 추가 작성한다.
        if (50 <= lastUsage)
            OutputDebugString(_T("CPU Usage is too high : %.2f"), dVal));
    }

    int GetLastUsage() { return lastUsage;  }


private:
    ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    int numProcessors;
    HANDLE self;

    int lastUsage;

    CPUChecker(void)
    {
        init();
    }
    /// Scope 제한을 위한 구현없이 선언만 된 복사생성자
    CPUChecker(const CPUChecker&);
    /// Scope 제한을 위한 구현없이 선언만 된 대입생성자
    CPUChecker& operator=(const CPUChecker&);

    void init() {
        SYSTEM_INFO sysInfo;
        FILETIME ftime, fsys, fuser;
        GetSystemInfo(&sysInfo);
        numProcessors = sysInfo.dwNumberOfProcessors;

        GetSystemTimeAsFileTime(&ftime);
        memcpy(&lastCPU, &ftime, sizeof(FILETIME));


        self = GetCurrentProcess();
        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&lastSysCPU, &fsys, sizeof(FILETIME));
        memcpy(&lastUserCPU, &fuser, sizeof(FILETIME));
    }

    double getCurrentValue() {
        FILETIME ftime, fsys, fuser;
        ULARGE_INTEGER now, sys, user;
        double percent;

        GetSystemTimeAsFileTime(&ftime);
        memcpy(&now, &ftime, sizeof(FILETIME));


        GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser);
        memcpy(&sys, &fsys, sizeof(FILETIME));
        memcpy(&user, &fuser, sizeof(FILETIME));
        percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart);
        percent /= (now.QuadPart - lastCPU.QuadPart);
        percent /= numProcessors;
        lastCPU = now;
        lastUserCPU = user;
        lastSysCPU = sys;

        lastUsage = static_cast<int>(percent * 100);

        return percent * 100;
    }

};

반응형

댓글