![](/img/trans.png)
[英]how to calculate the total memory and CPU usage consumed by an application in c++?
[英]C++ figure out CPU/Memory usage
我有一个名为 ./blah 的 C++ 应用程序(我有源代码)
当我运行 ./blah
我可以运行“top”并查看“./blah”使用了多少内存和 CPU。
现在,无论如何“./blah”可以访问该信息本身? 即当我运行 ./blah 时,我希望它每秒转储一次它的 CPU 和内存使用情况。 我应该使用什么库来做到这一点?
我在 MacOSX 上; 但我更喜欢一个也适用于 Linux 的解决方案。
谢谢!
你想要getrusage()
。 从手册页:
int getrusage(int who, struct rusage *r_usage);
getrusage()
返回描述当前进程或其所有终止子进程使用的资源的信息。who
参数是RUSAGE_SELF
或RUSAGE_CHILDREN
。 将使用以下结构填充r_usage
指向的缓冲区:
struct rusage {
struct timeval ru_utime; /* user time used */
struct timeval ru_stime; /* system time used */
long ru_maxrss; /* integral max resident set size */
long ru_ixrss; /* integral shared text 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 */
};
Linux 在以下位置提供此信息:
/proc/<pid>/stat
您可以通过以下方式获取当前 pid:
getpid()
返回 pid_t。
这是我发现以合理格式显示该信息的一段代码: http : //brokestream.com/procstat.html
我不知道这是否适用于 Mac OSX。
编辑:Mac OS X 没有 procfs 文件系统,所以这不适用于 Mac OSX,抱歉!
如果您有兴趣使用此信息来分析您的应用程序,您可以在 OSX 上使用 dtrace:
http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.