本文介绍了如何从C ++程序内部衡量内存使用情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个c ++程序,是否有可能一次跟踪该程序正在使用多少内存?

Is it possible, for a c++ program, to track how much memory the program is using at one time?

例如,带有原型的函数:

For example, a function with a prototype:

int getEstimatedTotalMemoryUsage();

我想如果不可能的话,那么人们将不得不退出程序,进行系统调用并从那里检查结果.如果是这样,有哪些工具可用于此类目的?假设这是可能的,那就是.

I suppose if it's not possible, then one will have to get out of the program, do a system call and check the results from there. If so, what tools are available for such purposes? Assuming such a thing is possible, that is.

我正在使用linux,有什么工具可以为您做到这一点?

edit: I'm using linux, any tools that can do this for you?

推荐答案

是-使用POSIX getrusage .从 Linux手册页:

Yes - use POSIX getrusage. From the Linux man page:

#include <sys/time.h>
#include <sys/resource.h>

int getrusage(int who, struct rusage *usage);

说明

getrusage() 返回当前资源使用情况,用于 RUSAGE_SELF strong>或 RUSAGE_CHILDREN .前者要求当前进程使用的资源,后者则要求已终止并等待其子进程的孩子使用的资源.

Description

getrusage() returns current resource usages, for a who of either RUSAGE_SELF or RUSAGE_CHILDREN. The former asks for resources used by the current process, the latter for resources used by those of its children that have terminated and have been waited for.

struct rusage {
    struct timeval ru_utime; /* user time used */
    struct timeval ru_stime; /* system time used */
    long   ru_maxrss;        /* maximum resident set size */
    long   ru_ixrss;         /* integral shared memory size */
    long   ru_idrss;         /* integral unshared data size */
    long   ru_isrss;         /* integral unshared stack size */
    long   ru_minflt;        /* page reclaims */
    long   ru_majflt;        /* page faults */
    long   ru_nswap;         /* swaps */
    long   ru_inblock;       /* block input operations */
    long   ru_oublock;       /* block output operations */
    long   ru_msgsnd;        /* messages sent */
    long   ru_msgrcv;        /* messages received */
    long   ru_nsignals;      /* signals received */
    long   ru_nvcsw;         /* voluntary context switches */
    long   ru_nivcsw;        /* involuntary context switches */
};

这篇关于如何从C ++程序内部衡量内存使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:08