Syed Raza
Syed Raza

Reputation: 331

how to get cpu load linux java in percent precise and easy way?

Hi I am trying to get cpu load but I want to get just cpu load in percent. I have my code as shown below what the easiest way to get it as I try this code bu using 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);

hopes for your reply

thanks in advance

Upvotes: 2

Views: 4390

Answers (4)

cruze
cruze

Reputation: 21

This code using mpstat may be a solution

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);
      }
  }
}

Source

Upvotes: 1

alain.janinm
alain.janinm

Reputation: 20065

You can use this class :

        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();
                }
            }

        }

And then call :

    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;
            }
        }
    }

You can also take a look at other monitoring methods, hope it'll helps!

EDIT : (new Performance Monitor)

    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();
        }

    }

Upvotes: 0

Benjamin
Benjamin

Reputation: 574

Create a timer and take the sum of all Thread CPU times every second. Maybe this way:

long cpuTime = 0;
for (long id : ManagementFactory.getThreadMXBean ().getAllThreadIds ())
{
    cpuTime += ManagementFactory.getThreadMXBean ().getThreadCpuTime (id);
}

The CPU percentage is then the relative cpu time between the last and the current second divided by the timestamp difference.

Here's a simple example implementation of a CpuStats Class:

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);
      }
   }
}

Just retrieve getUsage() periodically.

Upvotes: 1

Vinesh
Vinesh

Reputation: 943

Its better to use Sigar API, you can use it for extracting different metrics. I have also used this for my application, you can refer the following link

http://support.hyperic.com/display/SIGAR/Home

Upvotes: 2

Related Questions