我正在编写跨平台C ++代码(Windows,Mac)。有没有办法检查当前过程正在使用多少内存?一个非常人为的片段来说明:

unsigned long m0 = GetMemoryInUse();
char *p = new char[ random_number ];
unsigned long m1 = GetMemoryInUse();
printf( "%d bytes used\n", (m1-m0) );

当然(M1-M0)应该等于Random_number,但是我正在尝试以更复杂的级别进行此操作,包括可能分配内存的可能的库呼叫。

以下不太优选:

  1. 使用valgrind(或它的同类)
  2. 使用自定义内存分配器跟踪分配的内存。
有帮助吗?

解决方案

  • 没有便携式方法可以做到这一点。
  • 对于大多数操作系统,甚至没有一种可靠的方法可以专门针对该操作系统。

其他提示

这是我写的一些代码,以便以便携式方式进行此操作。这不是完美的,但我认为它至少应该给指针,以便如何在几个平台上执行此操作。

(ps我定期使用OSX和Linux,并且知道这很好。我很少使用Windows,因此请注意适用于Windows子句,但我认为这是正确的。)

#ifdef __linux__
# include <sys/sysinfo.h>
#endif

#ifdef __APPLE__
# include <mach/task.h>
# include <mach/mach_init.h>
#endif

#ifdef _WINDOWS
# include <windows.h>
#else
# include <sys/resource.h>
#endif

/// The amount of memory currently being used by this process, in bytes.
/// By default, returns the full virtual arena, but if resident=true,
/// it will report just the resident set in RAM (if supported on that OS).
size_t memory_used (bool resident=false)
{
#if defined(__linux__)
    // Ugh, getrusage doesn't work well on Linux.  Try grabbing info
    // directly from the /proc pseudo-filesystem.  Reading from
    // /proc/self/statm gives info on your own process, as one line of
    // numbers that are: virtual mem program size, resident set size,
    // shared pages, text/code, data/stack, library, dirty pages.  The
    // mem sizes should all be multiplied by the page size.
    size_t size = 0;
    FILE *file = fopen("/proc/self/statm", "r");
    if (file) {
        unsigned long vm = 0;
        fscanf (file, "%ul", &vm);  // Just need the first num: vm size
        fclose (file);
       size = (size_t)vm * getpagesize();
    }
    return size;

#elif defined(__APPLE__)
    // Inspired by:
    // http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html
    struct task_basic_info t_info;
    mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
    task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
    size_t size = (resident ? t_info.resident_size : t_info.virtual_size);
    return size;

#elif defined(_WINDOWS)
    // According to MSDN...
    PROCESS_MEMORY_COUNTERS counters;
    if (GetProcessMemoryInfo (GetCurrentProcess(), &counters, sizeof (counters)))
        return counters.PagefileUsage;
    else return 0;

#else
    // No idea what platform this is
    return 0;   // Punt
#endif
}

您可以使用“内存池”模式。程序中的所有对象都可以从此池分配/dealslage loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce loce the Memory to lose。

我用过了 Sigar API 为了在主要平台上非常省力地获取各种系统相关信息。它也是开源(Apache)。确实,无需在这些相对琐碎但乏味的工作上重新发明轮子。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top