Is there a way to get the current cpu load under Java without using the JNI?
+2
A:
On linux you could just read the file /proc/loadavg, where the first three values represent the load averages. For Windows you probably have to stick to JNI.
welterde
2009-03-11 13:57:03
+14
A:
Use the ManagementFactory
to get an OperatingSystemMXBean
and call getSystemLoadAverage()
on it.
Joachim Sauer
2009-03-11 14:00:53
Weird. The getSystemLoadAverage link doesn't go to the anchor, but when I went in to edit it, it did work. Maybe the system now auto-replaces () with %28%29, even in anchors.
Michael Myers
2009-03-11 14:28:40
Well, when I edited it, I got it wrong the first time. Maybe we had a human race condition. Having the link seemed to make the answer even more perfect, though.
Bob Cross
2009-03-11 14:35:32
What I meant was that the link still shows as #getSystemLoadAverage%28%29. The Runtime.exec() link in Bombe's answer below has the same issue, and editing it shows exec(java.lang.String) instead of exec%28java.lang.String%29. Do either of those work for anyone else?
Michael Myers
2009-03-11 14:50:01
I don't think I see what you see: I'm running Firefox on Fedora 9 and I see this for the getSystemLoadAverage() link: http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()
Bob Cross
2009-03-11 14:54:53
Must be an IE7 thing then. (I wish I could use Firefox here.)
Michael Myers
2009-03-11 15:44:20
I am pretty sure this doesn't work on Windows XP.
Peter Lawrey
2009-03-16 07:04:07
+2
A:
This does involve JNI but there is a GPL library from Hyperic called Sigar that provides this information for all the major platforms, as well as a bunch of other OS-dependent stats like disk usage. It's worked great for us.
Alex Miller
2009-03-11 14:39:56
A:
If you're using the JRockit JVM you could use JMAPI. It works for JDK 1.4, 1.5 and 1.6.
System.out.println("Total CPU-usage:" + JVMFactory.getJVM().getMachine().getCPULoad());
System.out.println("Total JVM-load :" + JVMFactory.getJVM().getJVMLoad());
for(Iterator it = JVMFactory.getJVM().getMachine().getCPUs().iterator(); it.hasNext();)
{
CPU cpu = (CPU)it.next();
System.out.println("CPU Description: " + cpu.getDescription());
System.out.println("CPU Clock Frequency: " + cpu.getClockFrequency());
System.out.println("CPU Load: " + cpu.getLoad());
System.out.println();
}
Kire Haglin
2009-03-16 00:18:05