如何在方法执行期间获取加载CPU的值?

时间:2017-10-21 19:45:11

标签: java

我有一个简单的例子,其中包含一个方法“complexCalculation()”

class LoadCpuSolve{

    static void complexСalculation(){
        // Complexs calculations here...
    }

    public static void main(String... args){
        // Start complex calculations
        complexСalculation();

        // Information about cpu load here...
        System.out.println("While method execute, CPU load on" + valueCpuLoad+"%");
    }
}
  1. 可以吗?
  2. 我如何以programmaticaly方式进行?谢谢。

2 个答案:

答案 0 :(得分:2)

如果您使用的是Java 7或更高版本,则可以获取MBeanServer

MBeanServer server = ManagementFactory.getPlatformMBeanServer();

拥有服务器后,您可以查询服务器OperatingSystem MXBean:

ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");

获得ObjectName后,您可以查询操作系统的不同属性。例如SystemCpuLoad

AttributeList attrs = server.getAttributes(name, new String[]{"SystemCpuLoad"});

可以通过以下代码

检索属性的值
 Object value = null;
 if (!attrs.isEmpty()) {
     Attribute att = (Attribute) attrs.get(0);
     value = att.getValue();
 }

这是一个完整的例子,

     public class LoadCpuSolve {

        static void complexСalculation() {
            // Complexs calculations here...
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public static Object getValue(MBeanServer server, ObjectName name,
            String attrName) throws ReflectionException, InstanceNotFoundException {
            AttributeList attrs =
                server.getAttributes(name, new String[]{attrName});

            Object value = null;
            if (!attrs.isEmpty()) {
                Attribute att = (Attribute) attrs.get(0);
                value = att.getValue();
            }

            return value;
        }

        public static void main(
            String... args) throws Exception
            complexСalculation();

            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            ObjectName
                name = ObjectName.getInstance("java.lang:type=OperatingSystem");

            System.out.println(
                "While method execute, process CPU load on " + getValue(server, name,
                       "ProcessCpuLoad"));
            System.out.println(
                "While method execute, process CPU time on " + getValue(server, name,
                        "ProcessCpuTime"));
            System.out.println(
                "While method execute, system CPU load on " + getValue(server, name,
                        "SystemCpuLoad"));
        }
   }

答案 1 :(得分:0)

我希望Java JVM TI具有此类功能,因为分析工具也经常使用此API。但它不容易集成对它的支持,如果要求java类为此工作,性能将会下降。

见这里:https://docs.oracle.com/javase/7/docs/technotes/guides/jvmti/index.html