java - 获取内存和 CPU 使用率

标签 java cpu-usage memory-footprint

我想获得总物理内存、CPU 使用率和正在使用的内存量。我查看了 Runtime.freeMemory(),但这不是整个系统的空闲内存。

最佳答案

我知道我回答晚了,但我认为这段代码很有趣。 这是一个“封闭”代码的改编,在直接应用之前应该修改:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.Process;
import java.lang.Runtime;
import java.util.HashMap;

/**
 * SystemStatusReader is a collection of methods to read system status (cpu and memory)
 * 
 * @author Andreu Correa Casablanca
 */
public class SystemStatusReader
{
    public static final int CONSERVATIVE    = 0;
    public static final int AVERAGE     = 1;
    public static final int OPTIMISTIC  = 2;

    /**
     * cpuUsage gives us the percentage of cpu usage
     * 
     * mpstat -P ALL out stream example:
     *
     *  Linux 3.2.0-30-generic (castarco-laptop)    10/09/12    _x86_64_    (2 CPU)                 - To discard
     *                                                                                              - To discard
     *  00:16:30     CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle    - To discard
     *  00:16:30     all   17,62    0,03    3,55    0,84    0,00    0,03    0,00    0,00   77,93
     *  00:16:30       0   17,36    0,05    3,61    0,83    0,00    0,05    0,00    0,00   78,12
     *  00:16:30       1   17,88    0,02    3,49    0,86    0,00    0,01    0,00    0,00   77,74
     * 
     * @param measureMode Indicates if we want optimistic, convervative or average measurements.
     */
    public static Double cpuUsage (int measureMode) throws Exception {

        BufferedReader mpstatReader = null;

        String      mpstatLine;
        String[]    mpstatChunkedLine;

        Double      selected_idle;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process mpstatProcess = runtime.exec("mpstat -P ALL");

            mpstatReader = new BufferedReader(new InputStreamReader(mpstatProcess.getInputStream()));

            // We discard the three first lines
            mpstatReader.readLine();
            mpstatReader.readLine();
            mpstatReader.readLine();

            mpstatLine = mpstatReader.readLine();
            if (mpstatLine == null) {
                throw new Exception("mpstat didn't work well");
            } else if (measureMode == SystemStatusReader.AVERAGE) {
                mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");
                selected_idle = Double.parseDouble(mpstatChunkedLine[10]);
            } else {
                selected_idle   = (measureMode == SystemStatusReader.CONSERVATIVE)?200.:0.;
                Double candidate_idle;

                int i = 0;
                while((mpstatLine = mpstatReader.readLine()) != null) {
                    mpstatChunkedLine = mpstatLine.replaceAll(",", ".").split("\\s+");
                    candidate_idle = Double.parseDouble(mpstatChunkedLine[10]);

                    if (measureMode == SystemStatusReader.CONSERVATIVE) {
                        selected_idle = (selected_idle < candidate_idle)?selected_idle:candidate_idle;
                    } else if (measureMode == SystemStatusReader.OPTIMISTIC) {
                        selected_idle = (selected_idle > candidate_idle)?selected_idle:candidate_idle;
                    }
                    ++i;
                }
                if (i == 0) {
                    throw new Exception("mpstat didn't work well");
                }
            }
        } catch (Exception e) {
            throw e; // It's not desirable to handle the exception here
        } finally {
            if (mpstatReader != null) try {
                mpstatReader.close();
            } catch (IOException e) {
                // Do nothing
            }
        }

        return  100-selected_idle;
    }

    /**
     * memoryUsage gives us data about memory usage (RAM and SWAP)
     */
    public static HashMap<String, Integer> memoryUsage () throws Exception {
        BufferedReader freeReader = null;

        String      freeLine;
        String[]    freeChunkedLine;

        HashMap<String, Integer> usageData = new HashMap<String, Integer>();

        try {
            Runtime runtime = Runtime.getRuntime();
            Process freeProcess = runtime.exec("free -k"); // We measure memory in kilobytes to obtain a greater granularity

            freeReader = new BufferedReader(new InputStreamReader(freeProcess.getInputStream()));

            // We discard the first line
            freeReader.readLine();

            freeLine = freeReader.readLine();
            if (freeLine == null) {
                throw new Exception("free didn't work well");
            }
            freeChunkedLine = freeLine.split("\\s+");

            usageData.put("total", Integer.parseInt(freeChunkedLine[1]));

            freeLine = freeReader.readLine();
            if (freeLine == null) {
                throw new Exception("free didn't work well");
            }
            freeChunkedLine = freeLine.split("\\s+");

            usageData.put("used", Integer.parseInt(freeChunkedLine[2]));

            freeLine = freeReader.readLine();
            if (freeLine == null) {
                throw new Exception("free didn't work well");
            }
            freeChunkedLine = freeLine.split("\\s+");

            usageData.put("swap_total", Integer.parseInt(freeChunkedLine[1]));
            usageData.put("swap_used", Integer.parseInt(freeChunkedLine[2]));
        } catch (Exception e) {
            throw e;
        } finally {
            if (freeReader != null) try {
                freeReader.close();
            } catch (IOException e) {
                // Do nothing
            }
        }

        return usageData;
    }
}

关于java - 获取内存和 CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6284384/

相关文章:

amazon-web-services - 一周运行后,Elastic Beanstalk的CPU负载很高

r - 如何让 R 使用更多的 CPU 和内存?

c - Windows 上的内存占用

java - 我需要在使用尽可能少的内存的情况下快速找到该对象。我应该使用什么数据容器?

java - Spring通用服务

java - 什么是IndexOutOfBoundsException?我该如何解决?

java - 加载 XML 非常慢

java - 如何从 Hibernate MetadataSources 中发现完全限定的表列

linux - 如何将 "force"单线程遗留应用程序转为使用多个处理器

.net - 分析进程中加载​​的 native DLL 和程序集的内存占用的工具?