C ++弄清楚CPU /内存使用情况

时间:2010-02-16 23:36:09

标签: c++ linux macos resources

我有一个名为./blah的C ++应用程序(我有源代码)

当我跑./blah

我可以运行“顶部”,看看有多少内存和cpu“./blah”正在使用。

现在,无论如何“./blah”能够访问该信息吗?即当我运行./blah时,我希望它能够在每一次转出它的CPU和CPU。内存使用情况。我应该用什么库来做这个?

我在MacOSX上;但我更喜欢一种适用于Linux的解决方案。

谢谢!

3 个答案:

答案 0 :(得分:10)

你想要getrusage()。来自man page

  

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 */
 };

答案 1 :(得分:1)

Linux提供以下信息:

/proc/<pid>/stat

你可以通过以下方式获取当前的pid:

getpid()

返回pid_t。

以下是我发现的一段代码,以合理的格式显示该信息:http://brokestream.com/procstat.html

我不知道这是否适用于Mac OSX。

编辑:Mac OS X没有procfs文件系统,所以这对Mac OSX不起作用,对不起!

答案 2 :(得分:0)

如果您有兴趣使用此信息来分析您的应用程序,可以在OSX上使用dtrace:

http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html

相关问题