programing

프로세스 내부에서 CPU 및 메모리 소비량을 확인하는 방법

bestcode 2022. 8. 15. 21:14
반응형

프로세스 내부에서 CPU 및 메모리 소비량을 확인하는 방법

실행 중인 어플리케이션 내부에서 다음 퍼포먼스 파라미터를 결정하는 작업을 수행한 적이 있습니다.

  • 사용 가능한 총 가상 메모리
  • 현재 사용되고 있는 가상 메모리
  • 프로세스에서 현재 사용하고 있는 가상 메모리
  • 사용 가능한 총 RAM
  • 현재 사용 중인 RAM
  • RAM
  • 현재 사용 중인 CPU 비율
  • 프로세스에서 현재 사용 중인 CPU 비율

이 코드는 Windows와 Linux에서 실행되어야 했습니다.이것은 표준적인 작업인 것 같지만, 이 토픽에 관한 불완전한/잘못된/오래된 정보가 너무 많기 때문에 매뉴얼(WIN32 API, GNU 문서)과 인터넷에서 필요한 정보를 찾는 데 며칠이 걸렸습니다.

다른 사람들이 같은 문제를 겪지 않도록 하기 위해 흩어져 있는 모든 정보와 시행착오를 통해 발견한 것을 한 곳에 모아두는 것이 좋다고 생각했습니다.

창문들

위의 값 중 일부는 적절한 Win32 API에서 쉽게 구할 수 있습니다.완전성을 위해 여기에 나열하겠습니다.그러나 다른 것은 Performance Data Helper 라이브러리(PDH)에서 입수해야 합니다.이 라이브러리는 '의도적'이 아니기 때문에 업무에 많은 시행착오가 필요합니다(적어도 시간이 꽤 걸렸을 뿐인지도 모릅니다).

참고: 알기 쉽게 하기 위해 다음 코드에서는 모든 오류 검사가 생략되었습니다.리턴 코드를 확인하십시오.

  • 총 가상 메모리:

    #include "windows.h"
    
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;
    

    주의: 여기서 "Total Page File"이라는 이름은 약간 오해의 소지가 있습니다.실제로 이 파라미터는 스왑 파일과 설치된 RAM 크기인 "Virtual Memory Size"를 제공합니다.

  • 현재 사용되는 가상 메모리:

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

     DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;
    
  • 현재 프로세스에서 사용되는 가상 메모리:

    #include "windows.h"
    #include "psapi.h"
    
    PROCESS_MEMORY_COUNTERS_EX pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc));
    SIZE_T virtualMemUsedByMe = pmc.PrivateUsage;
    
  • 총 물리 메모리(RAM):

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

    DWORDLONG totalPhysMem = memInfo.ullTotalPhys;
    
  • 현재 사용되는 물리적 메모리:

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

    DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
    
  • 현재 프로세스에서 사용 중인 물리적 메모리:

    "현재 프로세스에서 사용되는 가상 메모리"와 동일한 코드입니다.

    SIZE_T physMemUsedByMe = pmc.WorkingSetSize;
    
  • 현재 사용 중인 CPU:

    #include "TCHAR.h"
    #include "pdh.h"
    
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuTotal;
    
    void init(){
        PdhOpenQuery(NULL, NULL, &cpuQuery);
        // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray()
        PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal);
        PdhCollectQueryData(cpuQuery);
    }
    
    double getCurrentValue(){
        PDH_FMT_COUNTERVALUE counterVal;
    
        PdhCollectQueryData(cpuQuery);
        PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal);
        return counterVal.doubleValue;
    }
    
  • 현재 프로세스에 사용되는 CPU:

    #include "windows.h"
    
    static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    static HANDLE self;
    
    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;
    
        return percent * 100;
    }
    

리눅스

은 Linux와 POSIX 이었습니다.getrusage()etc.이했지만, 가치를 수 .★ 저는 이 작업을 수행하려고 노력했지만, 의미 있는 가치를 얻지 못했습니다.커널 소스 자체를 확인해보니 Linux 커널 2.6 현재 API가 아직 완전히 구현되지 않은 것 같습니다!?

나는 의사 파일 을 읽는 ./proc아, 아, 아, 아, 아, 아, 아, 아, 아.

  • 총 가상 메모리:

    #include "sys/types.h"
    #include "sys/sysinfo.h"
    
    struct sysinfo memInfo;
    
    sysinfo (&memInfo);
    long long totalVirtualMem = memInfo.totalram;
    //Add other values in next statement to avoid int overflow on right hand side...
    totalVirtualMem += memInfo.totalswap;
    totalVirtualMem *= memInfo.mem_unit;
    
  • 현재 사용되는 가상 메모리:

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

    long long virtualMemUsed = memInfo.totalram - memInfo.freeram;
    //Add other values in next statement to avoid int overflow on right hand side...
    virtualMemUsed += memInfo.totalswap - memInfo.freeswap;
    virtualMemUsed *= memInfo.mem_unit;
    
  • 현재 프로세스에서 사용되는 가상 메모리:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    int parseLine(char* line){
        // This assumes that a digit will be found and the line ends in " Kb".
        int i = strlen(line);
        const char* p = line;
        while (*p <'0' || *p > '9') p++;
        line[i-3] = '\0';
        i = atoi(p);
        return i;
    }
    
    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmSize:", 7) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    
  • 총 물리 메모리(RAM):

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

    long long totalPhysMem = memInfo.totalram;
    //Multiply in next statement to avoid int overflow on right hand side...
    totalPhysMem *= memInfo.mem_unit;
    
  • 현재 사용되는 물리적 메모리:

    "Total Virtual Memory(가상 메모리 합계)"와 같은 코드입니다.

    long long physMemUsed = memInfo.totalram - memInfo.freeram;
    //Multiply in next statement to avoid int overflow on right hand side...
    physMemUsed *= memInfo.mem_unit;
    
  • 현재 프로세스에서 사용 중인 물리적 메모리:

    다음과 같이 "현재 프로세스에서 사용되는 가상 메모리"의 getValue()를 변경합니다.

    int getValue(){ //Note: this value is in KB!
        FILE* file = fopen("/proc/self/status", "r");
        int result = -1;
        char line[128];
    
        while (fgets(line, 128, file) != NULL){
            if (strncmp(line, "VmRSS:", 6) == 0){
                result = parseLine(line);
                break;
            }
        }
        fclose(file);
        return result;
    }
    

  • 현재 사용 중인 CPU:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    
    static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
    
    void init(){
        FILE* file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow,
            &lastTotalSys, &lastTotalIdle);
        fclose(file);
    }
    
    double getCurrentValue(){
        double percent;
        FILE* file;
        unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;
    
        file = fopen("/proc/stat", "r");
        fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow,
            &totalSys, &totalIdle);
        fclose(file);
    
        if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow ||
            totalSys < lastTotalSys || totalIdle < lastTotalIdle){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +
                (totalSys - lastTotalSys);
            percent = total;
            total += (totalIdle - lastTotalIdle);
            percent /= total;
            percent *= 100;
        }
    
        lastTotalUser = totalUser;
        lastTotalUserLow = totalUserLow;
        lastTotalSys = totalSys;
        lastTotalIdle = totalIdle;
    
        return percent;
    }
    
  • 현재 프로세스에 사용되는 CPU:

    #include "stdlib.h"
    #include "stdio.h"
    #include "string.h"
    #include "sys/times.h"
    #include "sys/vtimes.h"
    
    static clock_t lastCPU, lastSysCPU, lastUserCPU;
    static int numProcessors;
    
    void init(){
        FILE* file;
        struct tms timeSample;
        char line[128];
    
        lastCPU = times(&timeSample);
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        file = fopen("/proc/cpuinfo", "r");
        numProcessors = 0;
        while(fgets(line, 128, file) != NULL){
            if (strncmp(line, "processor", 9) == 0) numProcessors++;
        }
        fclose(file);
    }
    
    double getCurrentValue(){
        struct tms timeSample;
        clock_t now;
        double percent;
    
        now = times(&timeSample);
        if (now <= lastCPU || timeSample.tms_stime < lastSysCPU ||
            timeSample.tms_utime < lastUserCPU){
            //Overflow detection. Just skip this value.
            percent = -1.0;
        }
        else{
            percent = (timeSample.tms_stime - lastSysCPU) +
                (timeSample.tms_utime - lastUserCPU);
            percent /= (now - lastCPU);
            percent /= numProcessors;
            percent *= 100;
        }
        lastCPU = now;
        lastSysCPU = timeSample.tms_stime;
        lastUserCPU = timeSample.tms_utime;
    
        return percent;
    }
    

TODO: 기타 플랫폼

Linux 코드 중 /proc 의사 파일 시스템을 읽는 부분을 제외하고 Unix에서도 동작하는 것이 있습니다.에서는, 은 UNIX 의 부품이나 UNIX 의 부품으로 될 수 .getrusage()은은기 능용 ?용? 용??? ???

Mac OS X

총 가상 메모리

Mac OS X에서는 Linux와 같이 미리 설정된 스왑 파티션이나 파일을 사용하지 않기 때문에 까다롭습니다.다음은 Apple 문서 항목입니다.

주의: 대부분의 Unix 기반 운영 체제와 달리 Mac OS X는 가상 메모리에 미리 할당된 스왑 파티션을 사용하지 않습니다.대신 머신의 부트 파티션에서 사용 가능한 모든 공간을 사용합니다.

따라서 사용 가능한 가상 메모리의 양을 확인하려면 루트 파티션의 크기를 가져와야 합니다.다음과 같이 할 수 있습니다.

struct statfs stats;
if (0 == statfs("/", &stats))
{
    myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;
}

현재 사용된 가상 총계

"vm.swapusage" 키를 사용하여 syscl을 호출하면 스왑 사용에 대한 흥미로운 정보를 얻을 수 있습니다.

sysctl -n vm.swapusage
vm.swapusage: total = 3072.00M  used = 2511.78M  free = 560.22M  (encrypted)

위의 항에서 설명한 바와 같이 스왑이 더 필요한 경우 여기에 표시되는 총 스왑 사용량이 변경될 수 있습니다.즉, 실제로는 현재의 스왑 합계입니다.C++ 에서는, 다음의 방법으로 데이터를 조회할 수 있습니다.

xsw_usage vmusage = {0};
size_t size = sizeof(vmusage);
if( sysctlbyname("vm.swapusage", &vmusage, &size, NULL, 0)!=0 )
{
   perror( "unable to get swap usage by calling sysctlbyname(\"vm.swapusage\",...)" );
}

sysctl.h에서 선언된 "xsw_usage"는 문서화되어 있지 않은 것 같습니다.또, 이러한 값에 액세스 할 수 있는 보다 포터블한 방법이 있다고 생각됩니다.

프로세스에서 현재 사용하고 있는 가상 메모리

중인 는 을 하여 얻을 수 .task_info 현재 및 현재를 포함합니다.여기에는 프로세스의 현재 상주 크기와 현재 가상 크기가 포함됩니다.

#include<mach/mach.h>

struct task_basic_info t_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

if (KERN_SUCCESS != task_info(mach_task_self(),
                              TASK_BASIC_INFO, (task_info_t)&t_info,
                              &t_info_count))
{
    return -1;
}
// resident size is in t_info.resident_size;
// virtual size is in t_info.virtual_size;

사용 가능한 총 RAM

은 RAM을 하여 사용할 수 .sysctl시스템은 다음과 같이 기능합니다.

#include <sys/types.h>
#include <sys/sysctl.h>
...
int mib[2];
int64_t physical_memory;
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
length = sizeof(int64_t);
sysctl(mib, 2, &physical_memory, &length, NULL, 0);

현재 사용 중인 RAM

인 메모리 는 에서 수 .host_statistics시스템 기능

#include <mach/vm_statistics.h>
#include <mach/mach_types.h>
#include <mach/mach_init.h>
#include <mach/mach_host.h>

int main(int argc, const char * argv[]) {
    vm_size_t page_size;
    mach_port_t mach_port;
    mach_msg_type_number_t count;
    vm_statistics64_data_t vm_stats;

    mach_port = mach_host_self();
    count = sizeof(vm_stats) / sizeof(natural_t);
    if (KERN_SUCCESS == host_page_size(mach_port, &page_size) &&
        KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,
                                        (host_info64_t)&vm_stats, &count))
    {
        long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;

        long long used_memory = ((int64_t)vm_stats.active_count +
                                 (int64_t)vm_stats.inactive_count +
                                 (int64_t)vm_stats.wire_count) *  (int64_t)page_size;
        printf("free memory: %lld\nused memory: %lld\n", free_memory, used_memory);
    }

    return 0;
}

여기서 주의할 점은 Mac OS X에는 5종류의 메모리 페이지가 있다는 것입니다.그 예는 다음과 같습니다.

  1. 제자리에 잠겨 있어 스왑 아웃할 수 없는 유선 페이지
  2. 물리 메모리에 로드되고 있어 스왑이 비교적 어려운 액티브 페이지
  3. 메모리에 로드되어 있지만 최근 사용되지 않아 전혀 필요하지 않을 수 있는 비활성 페이지입니다.이들은 스와프 대상이 될 수 있습니다.이 메모리는, 아마 플래시 할 필요가 있습니다.
  4. 캐시된 페이지. 캐시된 페이지 중 어느 정도이며 쉽게 재사용될 수 있습니다.캐시된 메모리는 플래시할 필요가 없습니다.캐시된 페이지를 다시 활성화할 수 있습니다.
  5. 완전히 무료이며 바로 사용할 수 있는 무료 페이지입니다.

Mac OS X에서 실제 빈 메모리가 거의 표시되지 않을 수 있기 때문에 짧은 시간에 사용할 수 있는 용량을 나타내는 좋은 지표가 되지 않을 수 있습니다.

현재 프로세스에서 사용되고 있는 RAM

상기의 「현재 사용하고 있는 가상 메모리」를 참조해 주세요.같은 코드가 적용됩니다.

리눅스

Linux의 경우 이 정보는 /proc 파일시스템에서 이용할 수 있습니다.Linux 디스트리뷰션마다 적어도1개의 중요한 파일이 커스터마이즈 되는 것 같기 때문에 사용하는 텍스트 파일 포맷은 그다지 좋아하지 않습니다.ps의 출처를 잽싸게 보면 혼란이 드러납니다.

여기서 찾으시는 정보를 찾을 수 있습니다.

/syslog/meminfo에는 사용자가 찾는 시스템 전체의 정보가 대부분 포함되어 있습니다.여기에서는 MemTotal, MemFree, SwapTotalSwapFree에 관심이 있을 으로 생각합니다.

Anderson cxc # more /proc/meminfo
MemTotal:      4083948 kB
MemFree:       2198520 kB
Buffers:         82080 kB
Cached:        1141460 kB
SwapCached:          0 kB
Active:        1137960 kB
Inactive:       608588 kB
HighTotal:     3276672 kB
HighFree:      1607744 kB
LowTotal:       807276 kB
LowFree:        590776 kB
SwapTotal:     2096440 kB
SwapFree:      2096440 kB
Dirty:              32 kB
Writeback:           0 kB
AnonPages:      523252 kB
Mapped:          93560 kB
Slab:            52880 kB
SReclaimable:    24652 kB
SUnreclaim:      28228 kB
PageTables:       2284 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4138412 kB
Committed_AS:  1845072 kB
VmallocTotal:   118776 kB
VmallocUsed:      3964 kB
VmallocChunk:   112860 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

CPU 사용률을 높이기 위해서는 약간의 작업이 필요합니다.Linux 에서는 시스템 부팅 후 전체적인 CPU 사용률을 확인할 수 있습니다.이것에 대해서는, 아마 흥미가 없는 것 같습니다.최근 1초 또는 10초 동안의 CPU 사용률을 확인하려면 정보를 조회하여 직접 계산해야 합니다.

정보는 /syslog/stat에서 확인할 수 있습니다.이 문서는 http://www.linuxhowtos.org/System/procstat.htm;에 잘 나와 있습니다.이 문서는 4코어 박스에 기재되어 있습니다.

Anderson cxc #  more /proc/stat
cpu  2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0

먼저 시스템에서 사용 가능한 CPU(또는 프로세서 또는 프로세싱 코어)의 수를 결정해야 합니다.이를 수행하려면 'cpuN' 항목 수를 세십시오. 여기서 N은 0에서 시작하여 증분합니다.cpuN 행의 조합인 'cpu' 행은 세지 마십시오.이 예에서는 cpu0에서 cpu3까지 총 4개의 프로세서를 볼 수 있습니다.이제부터는 cpu0을 무시할 수 있습니다.cpu3 및 'cpu' 행에만 초점을 맞춥니다.

다음으로 이들 행의 4번째 숫자는 아이돌 시간의 측정값이며, 따라서 'cpu' 행의 4번째 숫자는 부트 시간 이후의 모든 프로세서의 총 아이돌 시간입니다.이 시간은 Linux "jiffies"로 측정되며, 각각 1/100초입니다.

그러나 총 유휴 시간은 중요하지 않습니다. 주어진 기간(예: 마지막 1초)의 유휴 시간을 고려합니다.이 파일을 1초 간격으로 두 번 읽어야 합니다.다음으로 행의 네 번째 값을 다르게 할 수 있습니다.예를 들어, 샘플을 가져와서 다음을 얻을 수 있습니다.

cpu  2330047 0 2365006 1063853632 9035 9463 96114 0

그 후 1초 후에 다음 샘플을 얻을 수 있습니다.

cpu  2330047 0 2365007 1063854028 9035 9463 96114 0

2개의 숫자를 빼면 396의 차이가 납니다.이는 CPU가 최근 1.00초 중 3.96초 동안 아이돌 상태임을 의미합니다.물론 프로세서 수로 나누어야 합니다. 3.96 / 4 = 0.99. 유휴 백분율(99% 유휴, 1% 사용 중)이 표시됩니다.

제 코드에는 360개의 엔트리의 링 버퍼가 있으며 이 파일을 초당 읽습니다.이를 통해 CPU 사용률을 최대 1시간까지 빠르게 계산할 수 있습니다.

프로세스 고유의 정보는 /proc/pid를 참조해야 합니다.pid에 관심이 없다면 /proc/self를 참조할 수 있습니다.

프로세스에서 사용하는 CPU는 /proc/self/stat에서 사용할 수 있습니다.이것은 단일 행으로 구성된 홀수 모양의 파일입니다.다음은 예를 제시하겠습니다.

19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0

여기서 중요한 데이터는 13번째와 14번째 토큰(여기서는 0과 770)입니다.13번째 토큰은 프로세스가 사용자 모드에서 실행한 jiffies 수입니다. 14번째 토큰은 프로세스가 커널 모드에서 실행한 jiffies 수입니다.2개를 더하면 CPU 사용률의 합계가 됩니다.

이 경우에도 이 파일을 정기적으로 샘플링하여 diff를 계산하여 시간 경과에 따른 프로세스의 CPU 사용량을 확인해야 합니다.

편집: 프로세스의 CPU 사용률을 계산할 때는 1) 프로세스의 스레드 수 2) 시스템의 프로세서 수를 고려해야 합니다.예를 들어 싱글 스레드 프로세스가 CPU의 25%만 사용하는 경우 이는 양호하거나 불량할 수 있습니다.싱글 프로세서 시스템에서는 양호하지만 4 프로세서 시스템에서는 불량입니다.즉, 프로세스가 항상 실행되고 CPU 사이클의 100%를 사용하고 있는 것을 의미합니다.

프로세스 고유의 메모리 정보에 대해서는, 다음과 같은 /proc/self/status 를 참조해 주세요.

Name:   whatever
State:  S (sleeping)
Tgid:   19340
Pid:    19340
PPid:   19115
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak:   676252 kB
VmSize:   651352 kB
VmLck:         0 kB
VmHWM:    420300 kB
VmRSS:    420296 kB
VmData:   581028 kB
VmStk:       112 kB
VmExe:     11672 kB
VmLib:     76608 kB
VmPTE:      1244 kB
Threads:        77
SigQ:   0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed:   0f
Mems_allowed:   1
voluntary_ctxt_switches:        6518
nonvoluntary_ctxt_switches:     6598

'Vm'으로 시작하는 항목은 다음과 같습니다.

  • VmPeak는 프로세스에서 사용되는 최대 가상 메모리 공간(1024바이트)입니다.
  • VmSize는 프로세스에서 사용되는 현재 가상 메모리 공간(kB)입니다.이 예에서는 651,352kB, 즉 약 636메가바이트로 상당히 큽니다.
  • VmRss는 프로세스의 주소 공간에 매핑된 메모리의 양 또는 프로세스의 상주 세트 크기입니다.이 크기는 상당히 작습니다(420,296 kB, 약 410 MB).차이점은 내 프로그램이 mmap()을 통해 636MB를 매핑했지만, 그 중 410MB에만 액세스했기 때문에 410MB의 페이지만 할당되었다는 것입니다.

유일하게 확실하지 않은 항목은 현재 프로세스에서 사용되고 있는 Swapspace입니다.이것이 가능한지 모르겠습니다.

리눅스

메모리와 로드 번호를 읽는 휴대용 방법은 입니다.

사용.

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

묘사

   Until Linux 2.3.16, sysinfo() used to return information in the
   following structure:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           char _f[22];             /* Pads structure to 64 bytes */
       };

   and the sizes were given in bytes.

   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
   is:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           unsigned long totalhigh; /* Total high memory size */
           unsigned long freehigh;  /* Available high memory size */
           unsigned int mem_unit;   /* Memory unit size in bytes */
           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
       };

   and the sizes are given as multiples of mem_unit bytes.

Windows 에서는, 다음의 코드로 CPU 사용율을 확인할 수 있습니다.

#include <windows.h>
#include <stdio.h>

//------------------------------------------------------------------------------------------------------------------
// Prototype(s)...
//------------------------------------------------------------------------------------------------------------------
CHAR cpuusage(void);

//-----------------------------------------------------
typedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );
static pfnGetSystemTimes s_pfnGetSystemTimes = NULL;

static HMODULE s_hKernel = NULL;
//-----------------------------------------------------
void GetSystemTimesAddress()
{
    if(s_hKernel == NULL)
    {
        s_hKernel = LoadLibrary(L"Kernel32.dll");
        if(s_hKernel != NULL)
        {
            s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, "GetSystemTimes");
            if(s_pfnGetSystemTimes == NULL)
            {
                FreeLibrary(s_hKernel);
                s_hKernel = NULL;
            }
        }
    }
}
//----------------------------------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------------------------------
// cpuusage(void)
// ==============
// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.
//----------------------------------------------------------------------------------------------------------------
CHAR cpuusage()
{
    FILETIME               ft_sys_idle;
    FILETIME               ft_sys_kernel;
    FILETIME               ft_sys_user;

    ULARGE_INTEGER         ul_sys_idle;
    ULARGE_INTEGER         ul_sys_kernel;
    ULARGE_INTEGER         ul_sys_user;

    static ULARGE_INTEGER     ul_sys_idle_old;
    static ULARGE_INTEGER  ul_sys_kernel_old;
    static ULARGE_INTEGER  ul_sys_user_old;

    CHAR usage = 0;

    // We cannot directly use GetSystemTimes in the C language
    /* Add this line :: pfnGetSystemTimes */
    s_pfnGetSystemTimes(&ft_sys_idle,    /* System idle time */
        &ft_sys_kernel,  /* system kernel time */
        &ft_sys_user);   /* System user time */

    CopyMemory(&ul_sys_idle  , &ft_sys_idle  , sizeof(FILETIME)); // Could been optimized away...
    CopyMemory(&ul_sys_kernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...
    CopyMemory(&ul_sys_user  , &ft_sys_user  , sizeof(FILETIME)); // Could been optimized away...

    usage  =
        (
        (
        (
        (
        (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
        (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
        )
        -
        (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)
        )
        *
        (100)
        )
        /
        (
        (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+
        (ul_sys_user.QuadPart   - ul_sys_user_old.QuadPart)
        )
        );

    ul_sys_idle_old.QuadPart   = ul_sys_idle.QuadPart;
    ul_sys_user_old.QuadPart   = ul_sys_user.QuadPart;
    ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;

    return usage;
}


//------------------------------------------------------------------------------------------------------------------
// Entry point
//------------------------------------------------------------------------------------------------------------------
int main(void)
{
    int n;
    GetSystemTimesAddress();
    for(n=0; n<20; n++)
    {
        printf("CPU Usage: %3d%%\r", cpuusage());
        Sleep(2000);
    }
    printf("\n");
    return 0;
}

Mac OS X - CPU

전체 CPU 사용량:

Mac OS X의 Retrieve 시스템 정보에서 다음을 수행합니다.

#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;

// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
   host_cpu_load_info_data_t cpuinfo;
   mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
   if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
   {
      unsigned long long totalTicks = 0;
      for(int i=0; i<CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];
      return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
   }
   else return -1.0f;
}

float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
  unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
  unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;
  float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
  _previousTotalTicks = totalTicks;
  _previousIdleTicks  = idleTicks;
  return ret;
}

Linux의 경우

또한 /proc/self/statm을 사용하여 키프로세스 메모리 정보를 포함한 한 줄의 번호를 얻을 수 있습니다.이는 proc/self/status에서 얻을 수 있는 긴 보고서 정보 목록보다 처리 속도가 빠릅니다.

proc(5) 참조

/proc/[pid]/statm

    Provides information about memory usage, measured in pages.
    The columns are:

        size       (1) total program size
                   (same as VmSize in /proc/[pid]/status)
        resident   (2) resident set size
                   (same as VmRSS in /proc/[pid]/status)
        shared     (3) number of resident shared pages (i.e., backed by a file)
                   (same as RssFile+RssShmem in /proc/[pid]/status)
        text       (4) text (code)
        lib        (5) library (unused since Linux 2.6; always 0)
        data       (6) data + stack
        dt         (7) dirty pages (unused since Linux 2.6; always 0)

QNX

이것은 "코드 위키페이지"와 같기 때문에 QNX 기술 자료에서 코드를 추가하고 싶습니다(주의: 이것은 내 작업은 아니지만 확인했더니 시스템에서 정상적으로 작동합니다).

CPU 사용률을 %로 가져오는 방법: http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5

#include <atomic.h>
#include <libc.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/iofunc.h>
#include <sys/neutrino.h>
#include <sys/resmgr.h>
#include <sys/syspage.h>
#include <unistd.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/debug.h>
#include <sys/procfs.h>
#include <sys/syspage.h>
#include <sys/neutrino.h>
#include <sys/time.h>
#include <time.h>
#include <fcntl.h>
#include <devctl.h>
#include <errno.h>

#define MAX_CPUS 32

static float Loads[MAX_CPUS];
static _uint64 LastSutime[MAX_CPUS];
static _uint64 LastNsec[MAX_CPUS];
static int ProcFd = -1;
static int NumCpus = 0;


int find_ncpus(void) {
    return NumCpus;
}

int get_cpu(int cpu) {
    int ret;
    ret = (int)Loads[ cpu % MAX_CPUS ];
    ret = max(0,ret);
    ret = min(100,ret);
    return( ret );
}

static _uint64 nanoseconds( void ) {
    _uint64 sec, usec;
    struct timeval tval;
    gettimeofday( &tval, NULL );
    sec = tval.tv_sec;
    usec = tval.tv_usec;
    return( ( ( sec * 1000000 ) + usec ) * 1000 );
}

int sample_cpus( void ) {
    int i;
    debug_thread_t debug_data;
    _uint64 current_nsec, sutime_delta, time_delta;
    memset( &debug_data, 0, sizeof( debug_data ) );
    
    for( i=0; i<NumCpus; i++ ) {
        /* Get the sutime of the idle thread #i+1 */
        debug_data.tid = i + 1;
        devctl( ProcFd, DCMD_PROC_TIDSTATUS,
        &debug_data, sizeof( debug_data ), NULL );
        /* Get the current time */
        current_nsec = nanoseconds();
        /* Get the deltas between now and the last samples */
        sutime_delta = debug_data.sutime - LastSutime[i];
        time_delta = current_nsec - LastNsec[i];
        /* Figure out the load */
        Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );
        /* Flat out strange rounding issues. */
        if( Loads[i] < 0 ) {
            Loads[i] = 0;
        }
        /* Keep these for reference in the next cycle */
        LastNsec[i] = current_nsec;
        LastSutime[i] = debug_data.sutime;
    }
    return EOK;
}

int init_cpu( void ) {
    int i;
    debug_thread_t debug_data;
    memset( &debug_data, 0, sizeof( debug_data ) );
/* Open a connection to proc to talk over.*/
    ProcFd = open( "/proc/1/as", O_RDONLY );
    if( ProcFd == -1 ) {
        fprintf( stderr, "pload: Unable to access procnto: %s\n",strerror( errno ) );
        fflush( stderr );
        return -1;
    }
    i = fcntl(ProcFd,F_GETFD);
    if(i != -1){
        i |= FD_CLOEXEC;
        if(fcntl(ProcFd,F_SETFD,i) != -1){
            /* Grab this value */
            NumCpus = _syspage_ptr->num_cpu;
            /* Get a starting point for the comparisons */
            for( i=0; i<NumCpus; i++ ) {
                /*
                * the sutime of idle thread is how much
                * time that thread has been using, we can compare this
                * against how much time has passed to get an idea of the
                * load on the system.
                */
                debug_data.tid = i + 1;
                devctl( ProcFd, DCMD_PROC_TIDSTATUS, &debug_data, sizeof( debug_data ), NULL );
                LastSutime[i] = debug_data.sutime;
                LastNsec[i] = nanoseconds();
            }
            return(EOK);
        }
    }
    close(ProcFd);
    return(-1);
}

void close_cpu(void){
    if(ProcFd != -1){
        close(ProcFd);
        ProcFd = -1;
    }
}

int main(int argc, char* argv[]){
    int i,j;
    init_cpu();
    printf("System has: %d CPUs\n", NumCpus);
    for(i=0; i<20; i++) {
        sample_cpus();
        for(j=0; j<NumCpus;j++)
        printf("CPU #%d: %f\n", j, Loads[j]);
        sleep(1);
    }
    close_cpu();
}

빈 메모리(!)를 입수하는 방법:http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <sys/types.h>

int main( int argc, char *argv[] ){
    struct stat statbuf;
    paddr_t freemem;
    stat( "/proc", &statbuf );
    freemem = (paddr_t)statbuf.st_size;
    printf( "Free memory: %d bytes\n", freemem );
    printf( "Free memory: %d KB\n", freemem / 1024 );
    printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
    return 0;
} 

C++ 프로젝트에서 다음 코드를 사용했는데 정상적으로 동작했습니다.

static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;

double percent;

numProcessors = sysInfo.dwNumberOfProcessors;

//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime; 
FILETIME SysuserTime; 
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  

//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)

percent = 100*(numerator/denomenator);

Linux 에서는 SysInfo의 프리램을 사용하거나 totalram에 대해 몇 가지 연산을 통해 "Total Available Physical Memory"를 얻을 수 없습니다.

이를 수행하려면 proc/meminfo를 읽고 kernel/git/torvalds/linux.git, /proc/meminfo: 사용 가능한 예상 메모리를 제공하는 것이 좋습니다.

많은 로드밸런싱 및 워크로드 배치 프로그램은 /proc/meminfo를 체크하여 사용 가능한 메모리의 양을 예측합니다.그들은 보통 10년 전에는 괜찮았지만 오늘날에는 틀릴 것이 거의 확실시되는 "free"와 "cached"를 더해서 이것을 한다.

이러한 견적은 /proc/meminfo에서 제공하는 것이 더 편리합니다.앞으로 상황이 바뀌면 한 곳에서만 바꾸면 된다.

가지 방법은 Adam Rosenfield의 "How do you determinate of Linux system RAM in C++?" 답변입니다.파일을 읽고 fscanf를 사용하여 회선을 가져옵니다(MemTotal 대신 MemAvailable을 선택합니다).

마찬가지로 사용되는 물리 메모리의 총량을 취득하려면 "사용"의 의미에 따라 totalram에서 freeram을 빼지 않고 memtotal에서 memavailable을 빼서 top 또는 htop에서 알 수 있는 것을 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process

반응형