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?
Thanks
Baschdi
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());
}}
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.
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?
This works nice on windows 10. Measuring cpu util of skype:
c:\Windows\system32\typeperf "\Process(Skype)\% processor time"