如何在 Java 中检查 CPU 和内存使用情况?

发布于 2024-07-05 01:55:17 字数 42 浏览 7 评论 0原文

我需要检查java中服务器的CPU和内存使用情况,有人知道如何做到吗?

I need to check CPU and memory usage for the server in java, anyone know how it could be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

往事随风而去 2024-07-12 01:55:17

对于Eclipse,您可以使用TPTP(测试和性能工具平台)来分析内存使用情况等。 更多信息

For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. more information

佞臣 2024-07-12 01:55:17

我想在现有答案中添加一条注释:

这些方法仅跟踪 JVM 内存。 实际过程可能会消耗更多内存。

java.nio.ByteBuffer.allocateDirect() 是一个函数/库,很容易被错过,并且确实分配了本机内存,这不属于 Java 内存管理的一部分。

在 Linux 上,您可以使用类似的方法来获取实际消耗的内存: https://linuxhint.com/check_memory_usage_process_linux/< /a>

I want to add a note to the existing answers:

These methods only keep track of JVM Memory. The actual process may consume more memory.

java.nio.ByteBuffer.allocateDirect() is a function/library, that is easily missed, and indeed allocated native memory, that is not part of the Java memory management.

On Linux, you may use something like this to get the actually consumed memory: https://linuxhint.com/check_memory_usage_process_linux/

终陌 2024-07-12 01:55:17

YourKit Java 分析器是一个出色的商业解决方案。 您可以在有关 CPU 分析 的文档中找到更多信息内存分析

The YourKit Java profiler is an excellent commercial solution. You can find further information in the docs on CPU profiling and memory profiling.

×纯※雪 2024-07-12 01:55:17

如果您使用的是 Tomcat,请查看 Psi Probe,它可让您监控内部和外部环境外部存储器消耗以及许多其他领域。

If you are using Tomcat, check out Psi Probe, which lets you monitor internal and external memory consumption as well as a host of other areas.

郁金香雨 2024-07-12 01:55:17

以下是一些计算当前内存使用量(以兆字节为单位)的简单代码:

double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));

Here is some simple code to calculate the current memory usage in megabytes:

double currentMemory = ( (double)((double)(Runtime.getRuntime().totalMemory()/1024)/1024))- ((double)((double)(Runtime.getRuntime().freeMemory()/1024)/1024));
吹梦到西洲 2024-07-12 01:55:17

我还会添加以下方法来跟踪 CPU 负载:

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

double getCpuLoad() {
    OperatingSystemMXBean osBean =
        (com.sun.management.OperatingSystemMXBean) ManagementFactory.
        getPlatformMXBeans(OperatingSystemMXBean.class);
    return osBean.getProcessCpuLoad();
}

您可以阅读更多内容 此处

I would also add the following way to track CPU Load:

import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;

double getCpuLoad() {
    OperatingSystemMXBean osBean =
        (com.sun.management.OperatingSystemMXBean) ManagementFactory.
        getPlatformMXBeans(OperatingSystemMXBean.class);
    return osBean.getProcessCpuLoad();
}

You can read more here

有木有妳兜一样 2024-07-12 01:55:17

如果您使用此处许多答案中发布的运行时/总内存解决方案(我已经做了很多次),如果您想要相当准确/一致的结果,请务必首先强制执行两次垃圾收集。

为了提高效率,Java 通常允许垃圾在强制 GC 之前填满所有内存,即使如此,它通常也不是完整的 GC,因此,runtime.freeMemory() 的结果始终介于“实际”可用内存量和 0 之间 第一次GC

并没有得到全部,而是得到了大部分。

好处是,如果您只执行 freeMemory() 调用,您将得到一个绝对无用且变化很大的数字,但如果首先执行 2 个 gc,则这是一个非常可靠的指标。 它还使例程变慢(可能是几秒)。

If you use the runtime/totalMemory solution that has been posted in many answers here (I've done that a lot), be sure to force two garbage collections first if you want fairly accurate/consistent results.

For effiency Java usually allows garbage to fill up all of memory before forcing a GC, and even then it's not usually a complete GC, so your results for runtime.freeMemory() always be somewhere between the "real" amount of free memory and 0.

The first GC doesn't get everything, it gets most of it.

The upswing is that if you just do the freeMemory() call you will get a number that is absolutely useless and varies widely, but if do 2 gc's first it is a very reliable gauge. It also makes the routine MUCH slower (seconds, possibly).

逐鹿 2024-07-12 01:55:17

JConsole 是监视正在运行的 Java 应用程序的简单方法,您也可以使用探查器来获取有关您的应用程序的更多详细信息。 我喜欢使用 NetBeans Profiler 来实现此目的。

JConsole is an easy way to monitor a running Java application or you can use a Profiler to get more detailed information on your application. I like using the NetBeans Profiler for this.

绝情姑娘 2024-07-12 01:55:17

从 Java 1.5 开始,JDK 附带了一个新工具: JConsole ,它可以显示任何 1.5 或更高版本 JVM 的 CPU 和内存使用情况。 它可以绘制这些参数的图表,导出到 CSV,显示加载的类数量、实例数量、死锁、线程等...

Since Java 1.5 the JDK comes with a new tool: JConsole wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...

疯狂的代价 2024-07-12 01:55:17

Java 的 Runtime 对象可以报告JVM 的内存使用情况。 对于 CPU 消耗,您必须使用外部实用程序,例如 Unix 的 top 或 Windows 进程管理器。

Java's Runtime object can report the JVM's memory usage. For CPU consumption you'll have to use an external utility, like Unix's top or Windows Process Manager.

请你别敷衍 2024-07-12 01:55:17

JMX,提供的 MXBeans(ThreadMXBean 等)将为您提供内存和 CPU 使用情况。

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
operatingSystemMXBean.getSystemCpuLoad();

JMX, The MXBeans (ThreadMXBean, etc) provided will give you Memory and CPU usages.

OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
operatingSystemMXBean.getSystemCpuLoad();
送你一个梦 2024-07-12 01:55:17

对于内存使用情况,以下方法可行;

long total = Runtime.getRuntime().totalMemory();
long used  = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

对于 CPU 使用情况,您需要使用外部应用程序来测量它。

For memory usage, the following will work,

long total = Runtime.getRuntime().totalMemory();
long used  = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

For CPU usage, you'll need to use an external application to measure it.

梦里寻她 2024-07-12 01:55:17

来自此处

    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
    long prevUpTime = runtimeMXBean.getUptime();
    long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
    double cpuUsage;
    try
    {
        Thread.sleep(500);
    }
    catch (Exception ignored) { }

    operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long upTime = runtimeMXBean.getUptime();
    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
    long elapsedCpu = processCpuTime - prevProcessCpuTime;
    long elapsedTime = upTime - prevUpTime;

    cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
    System.out.println("Java CPU: " + cpuUsage);

From here

    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
    long prevUpTime = runtimeMXBean.getUptime();
    long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
    double cpuUsage;
    try
    {
        Thread.sleep(500);
    }
    catch (Exception ignored) { }

    operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long upTime = runtimeMXBean.getUptime();
    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
    long elapsedCpu = processCpuTime - prevProcessCpuTime;
    long elapsedTime = upTime - prevUpTime;

    cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
    System.out.println("Java CPU: " + cpuUsage);
一抹微笑 2024-07-12 01:55:17

如果您使用 Sun JVM,并且对应用程序的内部内存使用情况感兴趣(您的应用程序使用了多少分配的内存),我更喜欢打开 JVM 内置的垃圾收集日志记录。 您只需将 -verbose:gc 添加到启动命令中即可。

来自 Sun 文档:

命令行参数 -verbose:gc 每次打印信息
收藏。 请注意 -verbose:gc 输出的格式取决于
在 J2SE 平台的版本之间进行更改。 例如,这里是
大型服务器应用程序的输出:

[GC 325407K->83000K(776768K)​​,0.2300771 秒] 
  [GC 325816K→83372K(776768K)​​,0.2454258秒] 
  [完整GC 267628K->83769K(776768K)​​,1.8479984秒] 
  

这里我们看到两个次要集合和一个主要集合。 号码
箭头之前和之后

325407K->83000K(在第一行) 
  

表示垃圾前后存活对象的总大小
分别收集。 进行少量收集后,计数包括
不一定是活着的但也不能回收的对象
因为他们是直接活着的,或者因为他们在或
参考终身一代。 括号内的数字

(776768K)​​(在第一行) 
  

是总可用空间,不包括永久空间
Generation,即总堆减去幸存者空间之一。
次要收集大约花费了四分之一秒。

0.2300771 秒(在第一行) 
  

有关详细信息,请参阅:http://java.sun.com/docs/热点/gc5.0/gc_tuning_5.html

If you are using the Sun JVM, and are interested in the internal memory usage of the application (how much out of the allocated memory your app is using) I prefer to turn on the JVMs built-in garbage collection logging. You simply add -verbose:gc to the startup command.

From the Sun documentation:

The command line argument -verbose:gc prints information at every
collection. Note that the format of the -verbose:gc output is subject
to change between releases of the J2SE platform. For example, here is
output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections and one major one. The numbers
before and after the arrow

325407K->83000K (in the first line)

indicate the combined size of live objects before and after garbage
collection, respectively. After minor collections the count includes
objects that aren't necessarily alive but can't be reclaimed, either
because they are directly alive, or because they are within or
referenced from the tenured generation. The number in parenthesis

(776768K) (in the first line)

is the total available space, not counting the space in the permanent
generation, which is the total heap minus one of the survivor spaces.
The minor collection took about a quarter of a second.

0.2300771 secs (in the first line)

For more info see: http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html

╰つ倒转 2024-07-12 01:55:17

如果您专门寻找 JVM 中的内存:

Runtime runtime = Runtime.getRuntime();

NumberFormat format = NumberFormat.getInstance();

StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();

sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>");

但是,这些应该仅作为估计值......

If you are looking specifically for memory in JVM:

Runtime runtime = Runtime.getRuntime();

NumberFormat format = NumberFormat.getInstance();

StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();

sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>");

However, these should be taken only as an estimate...

一个人练习一个人 2024-07-12 01:55:17
import java.io.File;
import java.text.NumberFormat;

public class SystemInfo {

    private Runtime runtime = Runtime.getRuntime();

    public String info() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.osInfo());
        sb.append(this.memInfo());
        sb.append(this.diskInfo());
        return sb.toString();
    }

    public String osName() {
        return System.getProperty("os.name");
    }

    public String osVersion() {
        return System.getProperty("os.version");
    }

    public String osArch() {
        return System.getProperty("os.arch");
    }

    public long totalMem() {
        return Runtime.getRuntime().totalMemory();
    }

    public long usedMem() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }

    public String memInfo() {
        NumberFormat format = NumberFormat.getInstance();
        StringBuilder sb = new StringBuilder();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        sb.append("Free memory: ");
        sb.append(format.format(freeMemory / 1024));
        sb.append("<br/>");
        sb.append("Allocated memory: ");
        sb.append(format.format(allocatedMemory / 1024));
        sb.append("<br/>");
        sb.append("Max memory: ");
        sb.append(format.format(maxMemory / 1024));
        sb.append("<br/>");
        sb.append("Total free memory: ");
        sb.append(format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));
        sb.append("<br/>");
        return sb.toString();

    }

    public String osInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("OS: ");
        sb.append(this.osName());
        sb.append("<br/>");
        sb.append("Version: ");
        sb.append(this.osVersion());
        sb.append("<br/>");
        sb.append(": ");
        sb.append(this.osArch());
        sb.append("<br/>");
        sb.append("Available processors (cores): ");
        sb.append(runtime.availableProcessors());
        sb.append("<br/>");
        return sb.toString();
    }

    public String diskInfo() {
        /* Get a list of all filesystem roots on this system */
        File[] roots = File.listRoots();
        StringBuilder sb = new StringBuilder();

        /* For each filesystem root, print some info */
        for (File root : roots) {
            sb.append("File system root: ");
            sb.append(root.getAbsolutePath());
            sb.append("<br/>");
            sb.append("Total space (bytes): ");
            sb.append(root.getTotalSpace());
            sb.append("<br/>");
            sb.append("Free space (bytes): ");
            sb.append(root.getFreeSpace());
            sb.append("<br/>");
            sb.append("Usable space (bytes): ");
            sb.append(root.getUsableSpace());
            sb.append("<br/>");
        }
        return sb.toString();
    }
}
import java.io.File;
import java.text.NumberFormat;

public class SystemInfo {

    private Runtime runtime = Runtime.getRuntime();

    public String info() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.osInfo());
        sb.append(this.memInfo());
        sb.append(this.diskInfo());
        return sb.toString();
    }

    public String osName() {
        return System.getProperty("os.name");
    }

    public String osVersion() {
        return System.getProperty("os.version");
    }

    public String osArch() {
        return System.getProperty("os.arch");
    }

    public long totalMem() {
        return Runtime.getRuntime().totalMemory();
    }

    public long usedMem() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }

    public String memInfo() {
        NumberFormat format = NumberFormat.getInstance();
        StringBuilder sb = new StringBuilder();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        sb.append("Free memory: ");
        sb.append(format.format(freeMemory / 1024));
        sb.append("<br/>");
        sb.append("Allocated memory: ");
        sb.append(format.format(allocatedMemory / 1024));
        sb.append("<br/>");
        sb.append("Max memory: ");
        sb.append(format.format(maxMemory / 1024));
        sb.append("<br/>");
        sb.append("Total free memory: ");
        sb.append(format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));
        sb.append("<br/>");
        return sb.toString();

    }

    public String osInfo() {
        StringBuilder sb = new StringBuilder();
        sb.append("OS: ");
        sb.append(this.osName());
        sb.append("<br/>");
        sb.append("Version: ");
        sb.append(this.osVersion());
        sb.append("<br/>");
        sb.append(": ");
        sb.append(this.osArch());
        sb.append("<br/>");
        sb.append("Available processors (cores): ");
        sb.append(runtime.availableProcessors());
        sb.append("<br/>");
        return sb.toString();
    }

    public String diskInfo() {
        /* Get a list of all filesystem roots on this system */
        File[] roots = File.listRoots();
        StringBuilder sb = new StringBuilder();

        /* For each filesystem root, print some info */
        for (File root : roots) {
            sb.append("File system root: ");
            sb.append(root.getAbsolutePath());
            sb.append("<br/>");
            sb.append("Total space (bytes): ");
            sb.append(root.getTotalSpace());
            sb.append("<br/>");
            sb.append("Free space (bytes): ");
            sb.append(root.getFreeSpace());
            sb.append("<br/>");
            sb.append("Usable space (bytes): ");
            sb.append(root.getUsableSpace());
            sb.append("<br/>");
        }
        return sb.toString();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文