如何在方法执行过程中获得负载CPU的值



我有一个简单的例子,其中有一个方法"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. 我怎样才能用程序来做呢?谢谢

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

MBeanServer server = ManagementFactory.getPlatformMBeanServer();

一旦你有了服务器,你就可以查询服务器OperatingSystemMXBean:

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

我希望Java JVM TI具有这样的功能,因为评测工具也经常使用这个API。但集成对它的支持并不是那么容易,如果需要对java类进行工具化,性能就会下降。

请参见此处:https://docs.oracle.com/javase/7/docs/technotes/guides/jvmti/index.html

最新更新