如何找出Java中Java进程的CPU使用率 [英] How to figure out the cpu usage of a java-process in java

查看:136
本文介绍了如何找出Java中Java进程的CPU使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上搜索Java的可能性,以找出我的应用程序需要多少CPU,但可惜找不到解决方案。大多数人都提到 OperatingSystemMXBean,它可以在像linux这样的平台上运行,而不能在Windows上运行。我的应用程序将在多个操作系统上运行,但大多数情况下会在Windows上运行。那么,有没有办法找出同一平台上独立运行或支持Windows,Mac和Linux等多个平台的Java应用程序在同一运行时中的CPU使用率?

i've been searching the web for a possibility in java to figure out, how much cpu my application needs but sadly couldn't find a solution. Most of the people referred to "OperatingSystemMXBean" which works on platforms like linux, but not on windows. My application will run on multiple os but mostly on windows. So is there any way to figure out the cpu usage of a java-application in the same runtime which is platform independend or supports multiple platforms including windows, mac and linux?

谢谢

Baschdi

Thanks
Baschdi

推荐答案

我不同意您的说法。 OperatingSystemMXBean 在Windows上可用。只是有点隐藏。导入包时要小心。

I disagree with your statement. OperatingSystemMXBean is available on Windows. Just it's a bit hidden. Be careful with the package import. It's not the default offered by Eclipse.

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

 public class Test {

 public static void main(String[] args) {
     OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
     System.out.println(operatingSystemMXBean.getProcessCpuLoad());
}}

如果运行此摘录,可能会得到0.0。这不是故障。
这只是一个非常简单的程序,计算CPU负载可能需要一段时间。您可以在第一次调用时获得-1。

If you run this excerpt probably you obtain 0.0. It's not a malfunction. It's only a very light program and the cpu load may take a while to be calculated. You could obtain -1 on first invocations. Try it in your app, recovering the value in various instants.

如果我没记错的话,该类包含在rt.jar中。
您可能会发现在使用Eclipse IDE导入软件包时遇到的一些问题。
在这里您可以找到说明以及如何解决它。
为什么访问仅限于jre6 /lib/rt.jar for OperatingSystemMxBean?

If I'm not mistaken, this class is included in rt.jar. You may find some problems importing the package with Eclipse IDE. Here you can find the explanation and how to fix it. Why is access restricted to jre6/lib/rt.jar for OperatingSystemMxBean?

这篇关于如何找出Java中Java进程的CPU使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆