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

Basti
  • 1,117
  • 12
  • 32
  • You might find the answer here: http://stackoverflow.com/questions/16840594/finding-the-average-cpu-usage-for-windows-machine-in-java – Sason Ohanian Mar 22 '16 at 13:40

2 Answers2

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?

Community
  • 1
  • 1
RubioRic
  • 2,442
  • 4
  • 28
  • 35
  • 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 – Basti Mar 23 '16 at 14:45
  • 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. – RubioRic Mar 23 '16 at 15:02
-1

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

c:\Windows\system32\typeperf "\Process(Skype)\% processor time"
Sason Ohanian
  • 795
  • 5
  • 16
  • 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 – Basti Mar 23 '16 at 14:42