如何以精确且简单的方式获得linux java的cpu负载百分比?

如何以精确且简单的方式获得linux java的cpu负载百分比?,java,linux,Java,Linux,嗨,我试图得到cpu负载,但我想得到cpu负载的百分比。我有我的代码如下所示,当我使用net尝试这段代码时,最简单的方法是什么 OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) { method

嗨,我试图得到cpu负载,但我想得到cpu负载的百分比。我有我的代码如下所示,当我使用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);
希望你的答复


提前感谢

最好使用Sigar API,您可以使用它提取不同的度量。我也在我的应用程序中使用了这个,您可以参考以下链接


最好使用Sigar API,您可以使用它来提取不同的指标。我也在我的应用程序中使用了这个,您可以参考以下链接


创建一个计时器,并获取每秒所有线程CPU时间的总和。也许这样:

long cpuTime=0;
for(长id:ManagementFactory.getThreadMXBean().GetAllThreadId())
{
cpuTime+=ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
}
CPU百分比是最后一秒和当前第二秒之间的相对CPU时间除以时间戳差

下面是一个
CpuStats
类的简单示例实现:

公共类CpuStats
{
私有最终长线程ID;
private long lastCpuTime=0;
私有长lastPoll=0;
/**
*为单个线程创建CpuStats对象。
*@param threadId要监视的线程的id
* 
*/
公共CpuStats(长线程ID)
{
this.threadId=threadId;
lastCpuTime=getTotalTime();
lastPoll=System.nanoTime();
}
/**
*为所有线程创建CpuStatus对象。提供的统计信息会影响
*当前VM中的所有线程。
*/
公共CpuStats()
{
threadId=-1;
lastCpuTime=getTotalTime();
lastPoll=System.nanoTime();
}
私有长getRelativeTime()
{
long currentCpuTime=getTotalTime();
long ret=当前CPUTIME-最后一个CPUTIME;
lastCpuTime=currentCpuTime;
返回ret;
}
公共双用途()
{
long timeBefore=this.lastPoll;
lastPoll=System.nanoTime();
long relTime=getRelativeTime();
返回Math.max((double)relTime/(double)(lastPoll-timeBefore),0.0;
}
私有长GetToTime()
{
如果(线程ID==-1)
{
长cpuTime=0;
for(长id:ManagementFactory.getThreadMXBean().GetAllThreadId())
{
cpuTime+=ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
}
返回cpuTime;
}
其他的
{
返回ManagementFactory.getThreadMXBean().getThreadCpuTime(threadId);
}
}
}

只需定期检索
getUsage()

创建一个计时器,并每秒获取所有线程CPU时间的总和。也许这样:

long cpuTime=0;
for(长id:ManagementFactory.getThreadMXBean().GetAllThreadId())
{
cpuTime+=ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
}
CPU百分比是最后一秒和当前第二秒之间的相对CPU时间除以时间戳差

下面是一个
CpuStats
类的简单示例实现:

公共类CpuStats
{
私有最终长线程ID;
private long lastCpuTime=0;
私有长lastPoll=0;
/**
*为单个线程创建CpuStats对象。
*@param threadId要监视的线程的id
* 
*/
公共CpuStats(长线程ID)
{
this.threadId=threadId;
lastCpuTime=getTotalTime();
lastPoll=System.nanoTime();
}
/**
*为所有线程创建CpuStatus对象。提供的统计信息会影响
*当前VM中的所有线程。
*/
公共CpuStats()
{
threadId=-1;
lastCpuTime=getTotalTime();
lastPoll=System.nanoTime();
}
私有长getRelativeTime()
{
long currentCpuTime=getTotalTime();
long ret=当前CPUTIME-最后一个CPUTIME;
lastCpuTime=currentCpuTime;
返回ret;
}
公共双用途()
{
long timeBefore=this.lastPoll;
lastPoll=System.nanoTime();
long relTime=getRelativeTime();
返回Math.max((double)relTime/(double)(lastPoll-timeBefore),0.0;
}
私有长GetToTime()
{
如果(线程ID==-1)
{
长cpuTime=0;
for(长id:ManagementFactory.getThreadMXBean().GetAllThreadId())
{
cpuTime+=ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
}
返回cpuTime;
}
其他的
{
返回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 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;
            }
        }
    }

使用
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);
      }
  }
}
import java.io.*;
公共类CpuLoad{
公共静态void main(字符串参数[]){
int i=1;
浮动终局;
试一试{
//执行linux命令
进程p=Runtime.getRuntime().exec(“mpstat”);
BufferedReader in=新的BufferedReader(新的InputStreamReader(p.getInputStream());
字符串行=null;
//读取cpu空闲对应的行

而((line=in.readLine())!=null&&i此代码使用
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);
      }
  }
}
import java.io.*;
公共类CpuLoad{
公共静态void main(字符串参数[]){
int i=1;
浮动终局;
试一试{
//执行linux命令
进程p=Runtime.getRuntime().exec(“mpstat”);
BufferedReader in=新的BufferedReader(新的InputStreamReader(p.getInputStream());
字符串行=null;
//读取cpu空闲对应的行

虽然((line=in.readLine())!=null&&I它能给我准确的结果吗?是的,我想,我没有其他的比较基础,但我添加了用法