[英]how to get cpu load linux java in percent precise and easy way?
嗨,我正在嘗試獲取cpu負載,但我只想獲取cpu負載的百分比。 我有如下所示的代碼,這是在使用net嘗試此代碼bu時最簡單的方法
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);
希望您的答復
提前致謝
最好使用Sigar API,您可以將其用於提取不同的指標。 我也在我的應用程序中使用過此方法,您可以參考以下鏈接
這段使用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);
}
}
}
創建一個計時器,並每秒獲取所有線程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()
。
您可以使用此類:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.