15

我正在编写跨平台 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. 使用自定义内存分配器来跟踪分配的内存。
4

4 回答 4

18

这是我编写的一些代码,试图以可移植的方式执行此操作。它并不完美,但我认为它至少应该指出如何在多个平台上执行此操作。

(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
}
于 2008-12-16T20:11:07.450 回答
3

我已经使用SIGAR API在主要平台上非常便携地获取各种与系统相关的信息。它也是开源的(Apache)。在这些相对琐碎但乏味的工作上,真的没有必要重新发明轮子。

于 2008-12-16T20:33:37.403 回答
2
  • 没有便携的方法可以做到这一点。
  • 对于大多数操作系统,甚至没有一种可靠的方法可以针对该操作系统进行操作。
于 2008-12-16T19:57:27.367 回答
2

你可以使用“内存池”模式。程序中的所有对象都从这个池中分配/释放内存,这样你就可以了解你消耗了多少内存。

于 2008-12-16T20:00:00.593 回答