简体   繁体   English

如何读取java启动的进程的内存和cpu使用情况

[英]how to read the memory and cpu usage of a process started by java

i am starting a java process using我正在使用

Runtime.getRuntime().exec("java -jar javaprogarm.jar"); Runtime.getRuntime().exec("java -jar javaprogarm.jar");

i want to monitor the process that is started ram and CPU usage is there a way to do this in a cross platform manner?我想监视启动 ram 和 CPU 使用率的进程有没有办法以跨平台的方式做到这一点?

edit: to clarify i am not looking for the total system cpu and ram usage but rather the usage of that one process that i am starting.编辑:澄清一下,我不是在寻找系统 cpu 和 ram 的总使用量,而是在寻找我正在启动的那个进程的使用情况。 the question that was considered a duplicate is looking for the system cpu and ram not just a single process被认为是重复的问题是寻找系统 cpu 和 ram 而不仅仅是一个进程

Try this:尝试这个:

1) To hold all your running processes: 1) 保存所有正在运行的进程:

private List<String> processes = new ArrayList<String>();

2) To get all java running processes: 2)获取所有java运行进程:

private void getRunningProcesses() throws Exception {
    Process process = Runtime.getRuntime().exec("top -b -n1 -c");
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ( (line = br.readLine()) != null) {
        if( line.contains("java") ) processes.add( line );  
    }   
}

3) To get an information line from PID ( getRunningProcesses() first ): 3) 要从 PID 获取信息行(首先是 getRunningProcesses()):

private String getByPid( int pid ) {
    for ( String line : processes ) {
        if ( line.startsWith( String.valueOf( pid ) ) ) {
            return line;
        }
    }
    return "";
}

4) Now you have a line with all "top" information from that PID. 4) 现在您有一行包含来自该 PID 的所有“顶级”信息。 Get the CPU %:获取 CPU %:

private Double getCpuFromProcess( String process ) {
    //PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
    Double result = 0.0;
    String[] items = process.replace("  "," ").replace("  "," ").split(" ");
    result = Double.valueOf( items[8].replace(",", ".") );
    return result;
}

Done.完毕。

EDIT: Don't forget to clear processes list before each call.编辑:不要忘记在每次调用之前清除进程列表。

EDIT 2: Call编辑 2:调用

getRunningProcesses() , then getCpuFromProcess( getByPid( the_pid ) ) getRunningProcesses() ,然后getCpuFromProcess( getByPid( the_pid ) )

Runtime.getRuntime().freeMemory()
Runtime.getRuntime().totalMemory()

Maybe those methods will help you.也许这些方法会对你有所帮助。 The returned long values are measured by bytes.返回的 long 值以字节为单位。

Use the jvisualvm Tool.使用jvisualvm工具。
It is located in your Java JDK Installation in the bin Folder.它位于您的 Java JDK 安装的bin文件夹中。
It is a Graphical Tool, wher you can select a running Java VM.它是一个图形工具,您可以在其中选择正在运行的 Java VM。
In the Monitor Tab you can see CPU and Memory(Heap) usage.在监视器选项卡中,您可以看到 CPU 和内存(堆)使用情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM