0

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

1

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

This worked fine for windows. Thank you for the answer. Any suggestions about the other operating-systems? I need to support at least windows, mac and linux. Is com.sun.management.OperatingSystemMXBean accessable on those too and is it working? Besides that im using jdk8 to build this project, so i didn't even get the restriction
The restriction appears only as a warning if you are developing your code with Eclipse IDE. I think that this bean is available in those operative systems. I've tested it in Unix correctly but not in Mac but it's included in the java runtime. If you can execute java code, you have it available.
-1

This works nice on windows 10. Measuring cpu util of skype:

c:\Windows\system32\typeperf "\Process(Skype)\% processor time"

1 Comment

Sorry but i asked for a platform independend way to figure out the cpu usage of a java-application in java. Thats not quiet the answer i was searching for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.