获取内存和CPU使用情况

9

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


1
你有查看过关于这个问题的先前问题列表吗?请查看页面右侧的“相关”部分。如果已经涵盖了您需要的内容,请具体说明您缺少什么。 - Mat
一个Java小程序能够发现多少硬件细节? - Ethan Heilman
1
-1:显然没有做任何研究。有无数种方法可以找到这些信息,包括这个页面下面的“相关”一栏中的半数以上。当你写帖子时,同样的列表已经出现了。 - Lightness Races in Orbit
5个回答

6

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

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;
    }
}

这只能在*nix系统上运行,无法在Windows上运行。 - Kyle Falconer

4

Javadoc与二进制文件不匹配。我似乎在下载的JAR文件中找不到CpuPerc类。 - TheDoctor
@TheDoctor 奇怪。我不知道出了什么问题。看起来那些链接仍然是最新的。我知道它们必须使用本地代码,所以也许你的操作系统没有与SIGAR接口?我建议再检查一下细节--你是否在最新版本上?你是否有正确的导入?等等。 - Ryan Amos

2

内存CPU

CPU 示例:

static final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
      ...

    long start = threadBean.getCurrentThreadCpuTime();
     for (int i = 0; i < 10000000; i++) {
        ...
     }
    long finish = threadBean.getCurrentThreadCpuTime();

0
在Linux上,您可以将/proc/meminfo打开为文本文件并解析结果。

1
我需要一个跨平台的解决方案。 - Connor

0

如果是用于交互式使用,请通过“jconsole”使用JMX。 它可以显示漂亮的实时图形和许多其他诊断信息。


你能向我们阐述一下JMX使用的Java库和方法以获取内存信息,以及在我们自己的程序中,如何像JVisualVM或Jconsole.exe一样使用这些方法吗? - djangofan
我认为JConsole等只是通过TCP端口使用普通的JMX访问;而JVM本身公开了许多JMX属性。 - StaxMan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接