开发者

How to programmatically get the CPU utilization by the parent thread and sibling threads, from a worker thread?

开发者 https://www.devze.com 2023-04-03 01:38 出处:网络
My multi-threaded application (c++) uses pthreads. The application automatically generates t开发者_StackOverflowhreads and re-uses them on-demand, and allows a thread to be cancelled when it\'s been i

My multi-threaded application (c++) uses pthreads. The application automatically generates t开发者_StackOverflowhreads and re-uses them on-demand, and allows a thread to be cancelled when it's been idling for too long.

I have put in a "special thread" to capture statistical data for looking at application's performance, when subjected to different scenarios.

I can't wait for the process to exit, to know how much CPU was used.

Tried using this from the special thread, but the results did not seem to match the output of ps & top:

struct rusage ru;
    double utime, stime, ttime ;

if (getrusage(RUSAGE_SELF, &ru) == -1)
    return;

utime = ru.ru_utime.tv_sec + ( ru.ru_utime.tv_usec / 1000000 ); // Total CPU time used in user space
stime = ru.ru_stime.tv_sec + ( ru.ru_stime.tv_usec / 1000000 ); // Total CPU time used in kernel space
ttime = utime + stime; // Total CPU Utilization

Can you good hacks, tell me if there's a better way to do it, or the above is the correct method, and I am actually missing something else?

Thanks in advance.


If this is on Linux, you could use the special /proc file system to find out all sorts of interesting information about your process(es). I'm no expert but I'm quite sure cpu usage stats are in there somewhere.


OK I got it!

The code that I posted above, is fairly correct. My confusion was caused only by incorrect observation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号