Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get CPU usage for process by PID (top source code)

Tags:

macos

cpu

pid

How can I get CPU usage for process if i know only PID? MAXOS X

I looked through top utility source codes for MACOSX and I have found several important functions in libtop.c

/* Iterate through all processes and update their statistics. */
libtop_p_proc_table_read(boolean_t reg)

libtop_p_task_update() 

/* Get CPU usage statistics.    */
libtop_pinfo_update_cpu_usage() 

The problem is that I don't understand how they get %CPU usage from this huge amout of MACOS specific "mach kernel" system calls. Does anybody have solution for this?

I the source they get system_time, user_time , total_time.
I total_time is time from process start or what? Or may be total_time is equal 1 sec.

For example my results: for Opera Browser:

pid:1214 user:653.517582sec system:193.597306sec total:847.114888sec

Correct info from top utility:

PID COMMAND %CPU TIME
1214- Opera 8.0 14:04.52

I dont understand how to convert my results to 8.0%. Total time here is a sum of user time and system time. Total time is correct: 847sec is approx 14min 04 sec To get cpu usage percent i need something like idle time for all process.

I have already spend the whole day but without any advance.

like image 643
Vlad Avatar asked Feb 22 '11 11:02

Vlad


1 Answers

Look at GetCPUUsage() in https://chromium.googlesource.com/chromium/src/+/master/base/process/process_metrics_mac.cc for how this is implemented in chrome's task manager.

like image 105
thakis Avatar answered Sep 25 '22 16:09

thakis