如何才能看到内存使用情况

nod*_*nja 5 c++ memory macos

顶尖的语言是什么?我想编写一个c ++程序,可以看到各个进程在OSX中使用了多少内存.我不能使用/ proc,因为那不是在OSX上.top能够找出正在使用多少内存进程,因此它也不会使用它.我想知道它是如何发现的.

Jul*_*tta 5

需要深入研究源代码才能弄清楚,但 Top 使用 task_info() 调用来与 Mach 内核交互并收集内存统计信息。您可以在http://www.gnu.org/software/hurd/gnumach-doc/Task-Information.html阅读有关 task_info() 的一些基本正确的信息。我说大部分是正确的,因为我在 OS X 实现中至少发现了一个差异:内存大小以字节为单位,而不是以页为单位报告。

总而言之,您可以向 task_info() 传递一个“目标任务”(如果您想要有关程序本身的信息,则为 mach_task_self() ,否则使用 task_for_pid() 或processor_set_tasks())并告诉它您想要“基本信息”,即下面的类别哪些虚拟内存和常驻内存大小下降。然后task_info()用你想要的信息填充task_basic_info结构。

这是我编写的一个类来获取驻留内存大小。它还展示了如何使用 sysctl 获取有关系统的信息(在本例中,您有多少物理内存):

#include <sys/sysctl.h>
#include <mach/mach.h>
#include <cstdio>
#include <stdint.h>
#include <unistd.h>

////////////////////////////////////////////////////////////////////////////////
/*! Class for retrieving memory usage and system memory statistics on Mac OS X.
//  (Or probably any system using the MACH kernel.)
*///////////////////////////////////////////////////////////////////////////////
class MemoryInfo
{
    public:
        /** Total amount of physical memory (bytes) */
        uint64_t physicalMem;

        ////////////////////////////////////////////////////////////////////////
        /*! Constructor queries various memory properties of the system
        *///////////////////////////////////////////////////////////////////////
        MemoryInfo()
        {
            int mib[2];
            mib[0] = CTL_HW;
            mib[1] = HW_MEMSIZE;

            size_t returnSize = sizeof(physicalMem);
            if (sysctl(mib, 2, &physicalMem, &returnSize, NULL, 0) == -1)
                perror("Error in sysctl call");
        }

        ////////////////////////////////////////////////////////////////////////
        /*! Queries the kernel for the amount of resident memory in bytes.
        //  @return amount of resident memory (bytes)
        *///////////////////////////////////////////////////////////////////////
        static size_t Usage(void)
        {
            task_t targetTask = mach_task_self();
            struct task_basic_info ti;
            mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;

            kern_return_t kr = task_info(targetTask, TASK_BASIC_INFO_64,
                                         (task_info_t) &ti, &count);
            if (kr != KERN_SUCCESS) {
                printf("Kernel returned error during memory usage query");
                return -1;
            }

            // On Mac OS X, the resident_size is in bytes, not pages!
            // (This differs from the GNU Mach kernel)
            return ti.resident_size;
        }
};
Run Code Online (Sandbox Code Playgroud)


cob*_*bal 4

可能比您正在寻找的信息更多,但 OS X 中的 top 是在开源许可证下发布的:

http://opensource.apple.com/source/top/top-67/