views:

325

answers:

3

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 information 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!

+2  A: 

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!

Ninefingers
No `/proc` on OS X I'm afraid.
Carl Norum
@Carl thanks, I did a quick Google and edited that in before I saw your comment. There's a better solution below too.
Ninefingers
+8  A: 

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. The who parameter is either RUSAGE_SELF or RUSAGE_CHILDREN. The buffer to which r_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 */
 };
Carl Norum
+1 that looks more POSIX-compliant than my solution.
Ninefingers
Dumb question: how do I get % cpu out of that?
anon
You know how much user/system time are taken, divide that by real time and that's how much CPU time you used, right?
Carl Norum
Is that really the definition of %cpu? It seems soo simple.
anon
@anon, What would your definition be?
Carl Norum
A: 

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

Matt Curtis