Reputation: 5157
I am trying to get the CPU usage with getSystemCpuLoad() using OperatingSystemMXBean.
Code
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean mbean=(com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
double load;
while(true){
System.out.println(mbean.getSystemCpuLoad());
try {
Thread.sleep(1000);
}
catch ( InterruptedException e) {
e.printStackTrace();
}
}
}
How can I get the CPU usage of any particular process like firefox.exe ?
Upvotes: 0
Views: 881
Reputation: 4574
You can use some native lib or just parse response from:
Process process = Runtime.getRuntime().exec("top | grep firefox");
BufferedReader in = new BufferedReader(
new InputStreamReader(process.getInputStream()) );
But java not assumed for those tasks, I would recommend to consider C++ or C for it...
Upvotes: 0
Reputation: 304
By using OperatingSystemMXBean you'll only achieve reading the CPU Usage of a JVM. You wont be able to retrieve the cpu-load of other processes.
You would need to call system-functions, therefore you would need JNI.
But theres a library called sigar which you could use. Its licensed under the Apache License, Version 2.0.
Upvotes: 2