您好我正在尝试获取CPU负载,但我想以百分比得到cpu load。我有我的代码,如下所示,最简单的方法是使用net
尝试此代码OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
} // try
System.out.print(method.getName() + " = " + value);
希望你的回复
提前致谢
答案 0 :(得分:2)
最好使用Sigar API,您可以使用它来提取不同的指标。我也将此用于我的应用程序,您可以参考以下链接
答案 1 :(得分:1)
创建一个计时器并每秒获取所有线程CPU时间的总和。也许这样:
long cpuTime = 0;
for (long id : ManagementFactory.getThreadMXBean ().getAllThreadIds ())
{
cpuTime += ManagementFactory.getThreadMXBean ().getThreadCpuTime (id);
}
CPU百分比是最后一个和当前秒之间的相对cpu时间除以时间戳差。
以下是CpuStats
类的简单示例实现:
public class CpuStats
{
private final long threadId;
private long lastCpuTime = 0;
private long lastPoll = 0;
/**
* Creates a CpuStats object for a single thread.
* @param threadId The id of the thread to monitor
*
*/
public CpuStats (long threadId)
{
this.threadId = threadId;
lastCpuTime = getTotalTime ();
lastPoll = System.nanoTime ();
}
/**
* Creates a CpuStatus object for all threads. The supplied statistics affect
* all threads in the current VM.
*/
public CpuStats ()
{
threadId = -1;
lastCpuTime = getTotalTime ();
lastPoll = System.nanoTime ();
}
private long getRelativeTime ()
{
long currentCpuTime = getTotalTime ();
long ret = currentCpuTime - lastCpuTime;
lastCpuTime = currentCpuTime;
return ret;
}
public double getUsage ()
{
long timeBefore = this.lastPoll;
lastPoll = System.nanoTime ();
long relTime = getRelativeTime ();
return Math.max ((double)relTime / (double)(lastPoll - timeBefore), 0.0);
}
private long getTotalTime ()
{
if (threadId == -1)
{
long cpuTime = 0;
for (long id : ManagementFactory.getThreadMXBean ().getAllThreadIds ())
{
cpuTime += ManagementFactory.getThreadMXBean ().getThreadCpuTime (id);
}
return cpuTime;
}
else
{
return ManagementFactory.getThreadMXBean ().getThreadCpuTime (threadId);
}
}
}
定期检索getUsage()
。
答案 2 :(得分:1)
使用mpstat
的此代码可能是一个解决方案
import java.io.*;
public class CpuLoad {
public static void main(String args[]) {
int i=1;
float finalres;
try{
// execute the linux command
Process p=Runtime.getRuntime().exec("mpstat");
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
//read the row corresponding to cpu idle
while((line=in.readLine())!=null && i<4){
i++;
}
String res=line.substring(line.length()-5);
finalres=Float.parseFloat(res);
//convert the idle to cpuload
System.out.println("CPU load:"+(100-finalres)+"%");
}
catch(Exception e){
System.out.println(e);
}
}
}
答案 3 :(得分:0)
您可以使用此课程:
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
public class PerformanceMonitor {
static long lastSystemTime = 0;
static long lastProcessCpuTime = 0;
static int availableProcessors = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
public synchronized double getCpuUsage()
{
if ( lastSystemTime == 0 )
{
baselineCounters();
// return ;
}
long systemTime = System.nanoTime();
long processCpuTime = 0;
if ( ManagementFactory.getOperatingSystemMXBean() instanceof com.sun.management.OperatingSystemMXBean )
{
processCpuTime = ( (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean() ).getProcessCpuTime();
}
double cpuUsage = (double) (processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime )*100.0;
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
private void baselineCounters()
{
lastSystemTime = System.nanoTime();
if ( ManagementFactory.getOperatingSystemMXBean() instanceof com.sun.management.OperatingSystemMXBean )
{
lastProcessCpuTime = ( (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean() ).getProcessCpuTime();
}
}
}
然后致电:
public class Main {
public static PerformanceMonitor monitor = null;
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;
}
}
}
您还可以查看其他监控方法,希望它有所帮助!
编辑:(新的性能监视器)
import java.lang.management.ManagementFactory;
public class PerformanceMonitor {
static long lastSystemTime = 0;
static long lastProcessCpuTime = 0;
public static int availableProcessors = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
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();
}
}