Get CPU usage for a process using PID (top source code)

How can I get the processor load for a process if I only know the PID? MAXOS X

I looked at older source codes for MACOSX and I found some 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 utilization from this huge amount of MACOS specific “machine cores”. Does anyone have a solution for this?

I am the source that they get system_time, user_time, total_time.
Am I total_time from the start of the process or what? Or maybe total_time is 1 second.

For example, my results are: for the Opera browser:

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

Correct the information from the top utility:

-%

1214- 8.0 14: 04.52

, 8.0%. - . : 847 14 04 , - .

, - .

+5
4

, theses, - , .

, ( ).

, , , , , .

% CPU = (TIME2 - TIME1)/Waited_time;

, % CPU

, / ​​

+2

, top.c . total_time - p_total_time , . , .

, Mac OS X Mac Mac OS X Mac OS X , , , "Mac" "Mac OS X". , , , , , "Mac OS" - , "MACOS". Mac .

+1

, PID? MAXOS X

PID. PID, .

ps -aeo pcpu,pid,user,args|tail -n +2|sort -r|head -n 1

:

2,8 207 user1//Google Chrome.app/Contents/MacOS/Google Chrome -psn_0_20485

Java-, :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TopProcess {

    public static void main(String[] args) throws IOException {
        final String[] cmd = { "/bin/sh", "-c", "ps -aeo pcpu,pid,user,args|tail -n +2|sort -r|head -n 1" };
        String process;
        BufferedReader input = null;
        try{
            Process p = Runtime.getRuntime().exec(cmd); 
            input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((process = input.readLine()) != null) {
                System.out.println(process);
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            input.close();
        }
    }
}
0

All Articles