[英]C++ figure out CPU/Memory usage
I have a C++ app called ./blah (to which I have the source code)我有一个名为 ./blah 的 C++ 应用程序(我有源代码)
when I run ./blah当我运行 ./blah
I can run "top" and see how much memory & cpu "./blah" is using.我可以运行“top”并查看“./blah”使用了多少内存和 CPU。
Now, is there anyway for "./blah" to access that information itself?现在,无论如何“./blah”可以访问该信息本身? Ie when I run ./blah, I want it to every second dump out it's CPU & Memory usage.即当我运行 ./blah 时,我希望它每秒转储一次它的 CPU 和内存使用情况。 What library should I be using to do this?我应该使用什么库来做到这一点?
I'm on MacOSX;我在 MacOSX 上; but I'd prefer a solution that works on Linux too.但我更喜欢一个也适用于 Linux 的解决方案。
Thanks!谢谢!
You want getrusage()
.你想要getrusage()
。 From the man page :从手册页:
int getrusage(int who, struct rusage *r_usage);
getrusage()
returns information describing the resources utilized by the current process, or all its terminated child processes.getrusage()
返回描述当前进程或其所有终止子进程使用的资源的信息。 Thewho
parameter is eitherRUSAGE_SELF
orRUSAGE_CHILDREN
.who
参数是RUSAGE_SELF
或RUSAGE_CHILDREN
。 The buffer to whichr_usage
points will be filled in with the following structure:将使用以下结构填充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 provides this information in: Linux 在以下位置提供此信息:
/proc/<pid>/stat
And you can get the current pid with:您可以通过以下方式获取当前 pid:
getpid()
Returns pid_t.返回 pid_t。
Here's a piece of code I found displaying that info in a sensible format: http://brokestream.com/procstat.html这是我发现以合理格式显示该信息的一段代码: http : //brokestream.com/procstat.html
I don't know if this works on Mac OSX.我不知道这是否适用于 Mac OSX。
EDIT: Mac OS X doesn't have a procfs filesystem so this won't work for Mac OSX, sorry!编辑:Mac OS X 没有 procfs 文件系统,所以这不适用于 Mac OSX,抱歉!
If you are interested in using this information to profile your application, you could use dtrace on OSX:如果您有兴趣使用此信息来分析您的应用程序,您可以在 OSX 上使用 dtrace:
http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.