developer tip

사용 가능한 메모리 C ++ / g ++를 얻는 방법은 무엇입니까?

optionbox 2020. 11. 29. 10:15
반응형

사용 가능한 메모리 C ++ / g ++를 얻는 방법은 무엇입니까?


사용 가능한 메모리에 따라 버퍼를 할당하고 싶습니다. 따라서 처리를 수행하면 메모리 사용량이 증가하지만 여전히 사용 가능한 메모리 제한에 남아 있습니다. 사용 가능한 메모리를 얻는 방법이 있습니까 (가상 또는 실제 메모리 상태가 차이를 만들지 모르겠습니까?). 방법은 Windows, OS X, Linux 및 AIX에서 사용되므로 플랫폼 독립적이어야합니다. (가능하다면 실행 중에 변경되지 않는 애플리케이션에 사용 가능한 메모리를 할당하고 싶습니다).

편집 : 구성 가능한 메모리 할당으로 수행했습니다. 대부분의 OS가 우리를 위해 메모리를 관리하기 때문에 좋은 생각이 아니라는 것을 이해합니다.하지만 제 애플리케이션은 ETL 프레임 워크였습니다 (서버에서 사용하도록 의도되었지만 Adobe indesign 용 플러그인으로 데스크탑에서도 사용되었습니다). 그래서 저는 스왑을 사용하는 대신 창에서 잘못된 할당을 반환하고 다른 응용 프로그램이 실패하기 시작하기 때문에 문제가 발생했습니다. 그리고 내가 충돌을 피하는 법을 배웠을 때, 단지 우아하게 저하 시키려고 노력했습니다.


이 답변을 읽은 후 많은 사람들이 OP의 컴퓨터 메모리가 다른 사람에게 속한다는 입장을 취하는 것에 놀랐습니다. 그건 자신의 컴퓨터와 자신 이 주장을 가지고 다른 시스템을 중단하더라도, 그가 적합하다고으로 함께 할 수있는 메모리. 흥미로운 질문입니다. 좀 더 원시적 인 시스템에서는 이것을 memavail()말해 줄 수 있었습니다 . OP가 다른 시스템을 방해하지 않고 원하는만큼 많은 메모리를 차지하면 안되는 이유는 무엇입니까?

여기에 사용 가능한 메모리의 절반 미만을 할당하는 솔루션이 있습니다. 출력은 다음과 같습니다.

필수 FFFFFFFF

7FFFFFFF 필요

3FFFFFFF 필요

할당 된 메모리 크기 = 1FFFFFFF

#include <stdio.h>
#include <stdlib.h>

#define MINREQ      0xFFF   // arbitrary minimum

int main(void)
{
    unsigned int required = (unsigned int)-1; // adapt to native uint
    char *mem = NULL; 
    while (mem == NULL) {
        printf ("Required %X\n", required);
        mem = malloc (required);
        if ((required >>= 1) < MINREQ) {
            if (mem) free (mem);
            printf ("Cannot allocate enough memory\n");
            return (1);
        }
    }

    free (mem);
    mem = malloc (required);
    if (mem == NULL) {
        printf ("Cannot enough allocate memory\n");
        return (1);
    }
    printf ("Memory size allocated = %X\n", required);
    free (mem);
    return 0;
}

UNIX와 유사한 운영 체제에는 sysconf가 있습니다.

#include <unistd.h>

unsigned long long getTotalSystemMemory()
{
    long pages = sysconf(_SC_PHYS_PAGES);
    long page_size = sysconf(_SC_PAGE_SIZE);
    return pages * page_size;
}

Windows에는 다음이 있습니다 GlobalMemoryStatusEx.

#include <windows.h>

unsigned long long getTotalSystemMemory()
{
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    return status.ullTotalPhys;
}

So just do some fancy #ifdefs and you'll be good to go.


과학 소프트웨어를 위해 HPC에서이 작업을 수행하려는 이유가 있습니다. (게임, 웹, 비즈니스 또는 임베디드 소프트웨어가 아님). 과학 소프트웨어는 일상적으로 테라 바이트의 데이터를 통해 한 번의 계산 (또는 실행) (그리고 몇 시간 또는 몇 주 동안 실행)을 거치며이 모든 데이터는 메모리에 저장할 수 없습니다 (언젠가는 테라 바이트가 모든 PC의 표준이라고 말하면 또는 태블릿 또는 전화는 과학 소프트웨어가 페타 바이트 이상을 처리 할 것으로 예상되는 경우입니다.) 메모리의 양은 의미있는 방법 / 알고리즘의 종류를 지시 할 수도 있습니다. 사용자는 항상 메모리와 방법을 결정하고 싶지는 않습니다. 다른 사항에 대해 걱정할 필요가 있습니다. 따라서 프로그래머는 어떤 방법이 자동으로 작동할지 아니면 더 힘든 방법을 선택할지 결정하기 위해 사용 가능한 것이 무엇인지 (4Gb 또는 8Gb 또는 64Gb 또는 그 정도)에 대해 잘 알고 있어야합니다. 디스크가 사용되지만 메모리가 더 좋습니다. 그리고 그러한 소프트웨어의 사용자는 그러한 소프트웨어를 실행할 때 컴퓨터에서 너무 많은 일을하는 것을 권장하지 않습니다. 사실 그들은 종종 전용 컴퓨터 / 서버를 사용합니다.


이를 수행하는 플랫폼 독립적 인 방법은 없으며 운영 체제마다 다른 메모리 관리 전략을 사용합니다.

다음과 같은 다른 스택 오버플로 질문이 도움이 될 것입니다.

하지만주의해야합니다. 리눅스에서 사용 가능한 메모리에 대해 "실제"값을 얻는 것은 악명 높은 일입니다. 프로세스에서 사용하는 것으로 운영 체제가 표시하는 내용은 실제로 프로세스에 할당 된 내용을 보장하지 않습니다.

이는 하드웨어가 허용하는만큼 버퍼링하려는 라우터와 같은 임베디드 Linux 시스템을 개발할 때 흔히 발생하는 문제입니다. 다음은 Linux (C)에서이 정보를 얻는 방법을 보여주는 예제 링크입니다.


sysctl ( man 3 sysctl)을 사용하는 Mac OS X 예 :

#include <stdio.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/sysctl.h>

int main(void)
{
    int mib[2] = { CTL_HW, HW_MEMSIZE };
    u_int namelen = sizeof(mib) / sizeof(mib[0]);
    uint64_t size;
    size_t len = sizeof(size);

    if (sysctl(mib, namelen, &size, &len, NULL, 0) < 0)
    {
        perror("sysctl");
    }
    else
    {
        printf("HW.HW_MEMSIZE = %llu bytes\n", size);
    }
    return 0;
}

(may also work on other BSD-like operating systems ?)


The code below gives the total and free memory in Megabytes. Works for FreeBSD, but you should be able to use same/similar sysctl tunables on your platform and do to the same thing (Linux & OS X have sysctl at least)

#include <stdio.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>

int main(){
    int rc;
    u_int page_size;
    struct vmtotal vmt;
    size_t vmt_size, uint_size; 

    vmt_size = sizeof(vmt);
    uint_size = sizeof(page_size);

    rc = sysctlbyname("vm.vmtotal", &vmt, &vmt_size, NULL, 0);
    if (rc < 0){
       perror("sysctlbyname");
       return 1;
    }

    rc = sysctlbyname("vm.stats.vm.v_page_size", &page_size, &uint_size, NULL, 0);
    if (rc < 0){
       perror("sysctlbyname");
       return 1;
    }

    printf("Free memory       : %ld\n", vmt.t_free * (u_int64_t)page_size);
    printf("Available memory  : %ld\n", vmt.t_avm * (u_int64_t)page_size);

    return 0;
}

Below is the output of the program, compared with the vmstat(8) output on my system.

~/code/memstats % cc memstats.c 
~/code/memstats % ./a.out 
Free memory       : 5481914368
Available memory  : 8473378816
~/code/memstats % vmstat 
 procs      memory      page                    disks     faults         cpu
 r b w     avm    fre   flt  re  pi  po    fr  sr ad0 ad1   in   sy   cs us sy id
 0 0 0   8093M  5228M   287   0   1   0   304 133   0   0  112 9597 1652  2  1 97

The "official" function for this is was std::get_temporary_buffer(). However, you might want to test whether your platform has a decent implemenation. I understand that not all platforms behave as desired.


Instead of trying to guess, have you considered letting the user configure how much memory to use for buffers, as well as assuming somewhat conservative defaults? This way you can still run (possibly slightly slower) with no override, but if the user know there is X memory available for the app they can improve performance by configuring that amount.


Linux currently free memory: sysconf(_SC_AVPHYS_PAGES) and get_avphys_pages()

The total RAM was covered at https://stackoverflow.com/a/2513561/895245 with sysconf(_SC_PHYS_PAGES);.

Both sysconf(_SC_AVPHYS_PAGES) and get_avphys_pages() are glibc extensions to POSIX that give instead the total currently available RAM pages.

You then just have to multiply them by sysconf(_SC_PAGE_SIZE) to obtain the current free RAM.

Minimal runnable example at: C - Check available free RAM?

참고URL : https://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g

반응형