Reputation: 331
hi i am trying to get cpu load but i am getting per value more then 100% not understanding what wrong i am doing .. .
as i am using core i3 and having two Virtual machines on it and on one VM i am doing this task my source code is,
public class PerformanceMonitor {
static long lastSystemTime = 0;
static long lastProcessCpuTime = 0;
public static int availableProcessors = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
// public static int availableProcessors = Runtime.getRuntime().availableProcessors();
public synchronized double getCpuUsage()
{
ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
if ( lastSystemTime == 0 )
{
baselineCounters();
// return ;
}
long systemTime = System.nanoTime();
long processCpuTime = 0;
processCpuTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
double cpuUsage = (double) (processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime )*100.0;
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
private void baselineCounters()
{
lastSystemTime = System.nanoTime();
lastProcessCpuTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
}
}
and i am using this class in my code ,
public static void main(String[] args) {
monitor = new PerformanceMonitor();
for(int i=0 ; i<10000 ; i++){
start();
double usage = monitor.getCpuUsage();
if(usage!=0)System.out.println("Current CPU usage in pourcentage : "+usage);
}
}
private static void start() {
int count=0;
for(int i=0 ; i<100000 ; i++){
count=(int) Math.random()*100;
}
}
}
i am getting output like this,
Current CPU usage in pourcentage : 114.32926829268293
Current CPU usage in pourcentage : 48.70208931963182
Current CPU usage in pourcentage : 193.08746862328633
Current CPU usage in pourcentage : 236.85457129322594
hopes for your suggestions thanks in advance
Upvotes: 0
Views: 655
Reputation: 533492
I suspect the interval is too short. The cpu counters on linux only update 100 times per second and you could be performing the loop in about 1/100th of a second meaning you get a very large error. Try increasing the length of the loop so it is a few seconds long.
I made the test longer and removed the / availableProcessors
and I get numbers like this
Current CPU usage in percentage : 99.95763231535723
Current CPU usage in percentage : 99.94895863534565
Current CPU usage in percentage : 99.40642907762789
Current CPU usage in percentage : 99.96184668521532
Current CPU usage in percentage : 99.89017532820115
Current CPU usage in percentage : 99.91157680329947
Current CPU usage in percentage : 99.96919753553432
Current CPU usage in percentage : 99.94121334997978
Upvotes: 1