C++ figure out CPU/Memory usage
I have a C++ app called ./blah (to which I have the source code)
when I run ./blah
I can run "top" and see how much memory & cpu "./blah" is using.
Now, is there anyway for "./blah" to access that informatio开发者_开发问答n itself? I.e. when I run ./blah, I want it to every second dump out it's CPU & Memory usage. What library should I be using to do this?
I'm on MacOSX; but I'd prefer a solution that works on Linux too.
Thanks!
You want 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. Thewho
parameter is eitherRUSAGE_SELF
orRUSAGE_CHILDREN
. The buffer to whichr_usage
points will be filled in with the following structure:
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:
/proc/<pid>/stat
And you can get the current pid with:
getpid()
Returns pid_t.
Here's a piece of code I found displaying that info in a sensible format: http://brokestream.com/procstat.html
I don't know if this works on Mac OSX.
EDIT: Mac OS X doesn't have a procfs filesystem so this won't work for Mac OSX, sorry!
If you are interested in using this information to profile your application, you could use dtrace on OSX:
http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html
精彩评论