/* FIXME: This code sometimes fails with an "org.jinterop.dcom.common.JIException: An internal error occurred. [0x8001FFFF]" * on Windows 2008 */ public int getCPUUsage() throws JIException { System.gc(); JIVariant results[] = service_dispatch.callMethodA( "Get", new Object[] { new JIString("Win32_PerfRawData_PerfOS_Processor.Name='_Total'"), new Integer(0), JIVariant.OPTIONAL_PARAM() }); IJIDispatch wbemObject_dispatch = (IJIDispatch) JIObjectFactory.narrowObject((results[0]).getObjectAsComObject()); long ppt = Long.parseLong( wbemObject_dispatch.get("PercentProcessorTime").getObjectAsString().getString()); long tss = Long.parseLong( wbemObject_dispatch.get("TimeStamp_Sys100NS").getObjectAsString().getString()); if (this.percentprocessortime == -1 && this.timestamp == -1) { this.percentprocessortime = ppt; this.timestamp = tss; return -1; } double load = (1 - ((double) (this.percentprocessortime - ppt) / (double) (this.timestamp - tss))) * 100; this.percentprocessortime = ppt; this.timestamp = tss; return (int) Math.round(load); }
private static double round(double d, int dec_places) { return ((double) Math.round(d * Math.pow(10, dec_places))) / Math.pow(10, dec_places); }