programing

Java에서 컴퓨터의 CPU, 메모리 및 디스크 사용량을 모니터링하려면 어떻게 해야 합니까?

itsource 2022. 7. 28. 22:48
반응형

Java에서 컴퓨터의 CPU, 메모리 및 디스크 사용량을 모니터링하려면 어떻게 해야 합니까?

자바에서 다음 시스템 정보를 감시하고 싶습니다.

  • 현재 CPU 사용률**(%)
  • 사용 가능한 메모리* (빈 용량/합계)
  • 사용 가능한 디스크 용량(사용 가능/합계)

    * JVM뿐만 아니라 시스템 전체에서 사용할 수 있는 전체 메모리를 의미합니다.

외부 프로그램을 호출하거나 JNI를 사용하지 않는 자체 코드를 사용하지 않는 크로스 플랫폼 솔루션(Linux, Mac 및 Windows)을 찾고 있습니다.실행 가능한 옵션이지만 이미 더 나은 솔루션을 가지고 있다면 OS 고유의 코드를 직접 관리하고 싶지 않습니다.

신뢰할 수 있는 크로스 플랫폼 방식으로 이를 수행할 수 있는 무료 라이브러리가 있다면 좋습니다(외부 전화를 걸거나 네이티브 코드 자체를 사용하더라도).

어떤 제안이라도 감사합니다.

확실히 하자면 자바 프로세스뿐만 아니라 시스템 전체의 현재 CPU 사용률을 알고 싶습니다.

SIGAR API는 제가 원하는 모든 기능을 하나의 패키지로 제공하므로, 지금까지의 질문에 대한 가장 좋은 답변입니다.다만, GPL에 근거해 라이센스를 취득하고 있기 때문에, 본래의 목적(클로즈드 소스, 시판 제품)으로 사용할 수 없습니다.하이퍼릭이 SIGAR에 상업적 사용을 허가할 수도 있지만, 저는 아직 조사하지 않았습니다.GPL 프로젝트에서는 향후 SIGAR를 꼭 검토하겠습니다.

현재의 요구는 다음과 같습니다.

  • 사용률의 CPU 사용률,OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors()CPU)
  • 메모리의는, 「」입니다.OperatingSystemMXBean.getTotalPhysicalMemorySize() ★★★★★★★★★★★★★★★★★」OperatingSystemMXBean.getFreePhysicalMemorySize()
  • 용량에 는, 「」를 참조해 주세요.File.getTotalSpace() ★★★★★★★★★★★★★★★★★」File.getUsableSpace()

제한 사항:

getSystemLoadAverage() 영역 할 수 .의 JMX 할 수 경우가 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」의 「JMX」가 보고되고 있습니다).getSystemLoadAverage()Windows の - 1 이 windows windows windows windows windows windows windows ) 。

원래 GPL로 라이센스가 부여되었지만 Apache 2.0으로 변경되어 일반적으로 비공개 소스 상용 제품에 사용할 수 있습니다.

가 이 글에서 언급한 것과 같이.SIGAR API 사용을 권장합니다.저는 SIGAR API를 제 어플리케이션 중 하나에서 사용하고 있는데 아주 좋습니다.안정적이고, 잘 지원되며, 유용한 예가 가득하다는 것을 알게 될 것입니다.이것은 오픈 소스이며, GPL 2 Apache 2.0 라이선스이것을 확인해 보세요.당신의 요구에 부응할 것 같습니다.

Java와 Sigar API를 사용하면 메모리, CPU, 디스크, 부하 평균, 네트워크 인터페이스 정보와 메트릭, 프로세스 테이블 정보, 루트 정보 등을 얻을 수 있습니다.

CPU와 RAM은 다음과 같이 입수할 수 있습니다.자세한 내용은 Management Factory를 참조하십시오.

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

private static void printUsage() {
  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.println(method.getName() + " = " + value);
    } // if
  } // for
}

JDK 1.7에서는 를 통해 시스템 CPU 및 메모리 사용량을 확인할 수 있습니다.이것은 와는 다르다.java.lang.management.OperatingSystemMXBean.

long getCommittedVirtualMemorySize()
// Returns the amount of virtual memory that is guaranteed to be available to the running process in bytes, or -1 if this operation is not supported.

long getFreePhysicalMemorySize()
// Returns the amount of free physical memory in bytes.

long getFreeSwapSpaceSize()
// Returns the amount of free swap space in bytes.

double getProcessCpuLoad()
// Returns the "recent cpu usage" for the Java Virtual Machine process.

long getProcessCpuTime()
// Returns the CPU time used by the process on which the Java virtual machine is running in nanoseconds.

double getSystemCpuLoad()
// Returns the "recent cpu usage" for the whole system.

long getTotalPhysicalMemorySize()
// Returns the total amount of physical memory in bytes.

long getTotalSwapSpaceSize()
// Returns the total amount of swap space in bytes.

외부 API 없이 네이티브 Java 숨김 기능만 있으면 완벽하게 동작합니다.

import com.sun.management.OperatingSystemMXBean;
...
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(
                OperatingSystemMXBean.class);
// What % CPU load this current JVM is taking, from 0.0-1.0
System.out.println(osBean.getProcessCpuLoad());

// What % load the overall system is at, from 0.0-1.0
System.out.println(osBean.getSystemCpuLoad());

이 기사 http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime를 보세요.

CPU 사용률을 얻으려면 몇 가지 간단한 계산만 하면 됩니다.

MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();

OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// Call an expensive task, or sleep if you are monitoring a remote process

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)
 percent = ((cpuAfter-cpuBefore)*100L)/
   (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

주의: Import해야 합니다.com.sun.management.OperatingSystemMXBean가 아니라java.lang.management.OperatingSystemMXBean.

2008년 승인된 답변은 SIGAR을 권장했습니다.다만, 2014년의 코멘트(@Alvaro)에 의하면, 다음과 같습니다.

Sigar 사용 시 주의하세요.x64 머신에 문제가 있습니다...Sigar 1.6.4가 크래시 입니다.EXCESSION_ACCESS_VIRONATION으로 라이브러리가 2010년 이후로 업데이트되지 않은 것 같습니다.

https://github.com/oshi/oshi 를 사용하는 것을 추천합니다.

또는 위에 언급된 답변.

디스크 공간의 경우 Java 6을 사용하는 경우 파일에서 getTotalSpacegetFreeSpace 메서드를 사용할 수 있습니다.Java 6을 사용하지 않는 경우 Apache Commons IO를 사용하여 어느 정도 이용할 수 있습니다.

유감스럽게도 CPU 사용률이나 메모리 사용률을 얻을 수 있는 크로스 플랫폼 방법은 모릅니다.

JMX를 통해 이미 많은 것을 이용할 수 있습니다.JMX는 Java 5에 내장되어 있으며 JDK와 함께 JMX 콘솔 뷰어를 포함하고 있습니다.

JMX를 사용하여 수동으로 모니터링하거나 Java에서 JMX 명령을 호출할 수 있습니다.

/* YOU CAN TRY THIS TOO */

import java.io.File;
 import java.lang.management.ManagementFactory;
// import java.lang.management.OperatingSystemMXBean;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.lang.management.RuntimeMXBean;
 import java.io.*;
 import java.net.*;
 import java.util.*;
 import java.io.LineNumberReader;
 import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import java.util.Random;



 public class Pragati
 {

     public static void printUsage(Runtime runtime)
     {
     long total, free, used;
     int mb = 1024*1024;

     total = runtime.totalMemory();
     free = runtime.freeMemory();
     used = total - free;
     System.out.println("\nTotal Memory: " + total / mb + "MB");
     System.out.println(" Memory Used: " + used / mb + "MB");
     System.out.println(" Memory Free: " + free / mb + "MB");
     System.out.println("Percent Used: " + ((double)used/(double)total)*100 + "%");
     System.out.println("Percent Free: " + ((double)free/(double)total)*100 + "%");
    }
    public static void log(Object message)
         {
            System.out.println(message);
         }

        public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount)
        {
             long end = System.nanoTime();
             long totalAvailCPUTime = cpuCount * (end-elapsedStartTime);
             long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime()-cpuStartTime;
             //log("Total CPU Time:" + totalUsedCPUTime + " ns.");
             //log("Total Avail CPU Time:" + totalAvailCPUTime + " ns.");
             float per = ((float)totalUsedCPUTime*100)/(float)totalAvailCPUTime;
             log( per);
             return (int)per;
        }

        static boolean isPrime(int n)
        {
     // 2 is the smallest prime
            if (n <= 2)
            {
                return n == 2;
            }
     // even numbers other than 2 are not prime
            if (n % 2 == 0)
            {
                return false;
            }
     // check odd divisors from 3
     // to the square root of n
         for (int i = 3, end = (int)Math.sqrt(n); i <= end; i += 2)
         {
            if (n % i == 0)
         {
         return false;
        }
        }
 return true;
}
    public static void main(String [] args)
    {
            int mb = 1024*1024;
            int gb = 1024*1024*1024;
             /* PHYSICAL MEMORY USAGE */
             System.out.println("\n**** Sizes in Mega Bytes ****\n");
            com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
            //RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
            //operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)
            java.lang.management.ManagementFactory.getOperatingSystemMXBean();
            long physicalMemorySize = os.getTotalPhysicalMemorySize();
            System.out.println("PHYSICAL MEMORY DETAILS \n");
            System.out.println("total physical memory : " + physicalMemorySize / mb + "MB ");
            long physicalfreeMemorySize = os.getFreePhysicalMemorySize();
            System.out.println("total free physical memory : " + physicalfreeMemorySize / mb + "MB");
            /* DISC SPACE DETAILS */
            File diskPartition = new File("C:");
            File diskPartition1 = new File("D:");
            File diskPartition2 = new File("E:");
            long totalCapacity = diskPartition.getTotalSpace() / gb;
            long totalCapacity1 = diskPartition1.getTotalSpace() / gb;
            double freePartitionSpace = diskPartition.getFreeSpace() / gb;
            double freePartitionSpace1 = diskPartition1.getFreeSpace() / gb;
            double freePartitionSpace2 = diskPartition2.getFreeSpace() / gb;
            double usablePatitionSpace = diskPartition.getUsableSpace() / gb;
            System.out.println("\n**** Sizes in Giga Bytes ****\n");
            System.out.println("DISC SPACE DETAILS \n");
            //System.out.println("Total C partition size : " + totalCapacity + "GB");
            //System.out.println("Usable Space : " + usablePatitionSpace + "GB");
            System.out.println("Free Space in drive C: : " + freePartitionSpace + "GB");
            System.out.println("Free Space in drive D:  : " + freePartitionSpace1 + "GB");
            System.out.println("Free Space in drive E: " + freePartitionSpace2 + "GB");
            if(freePartitionSpace <= totalCapacity%10 || freePartitionSpace1 <= totalCapacity1%10)
            {
                System.out.println(" !!!alert!!!!");
            }
            else
                System.out.println("no alert");

            Runtime runtime;
            byte[] bytes;
            System.out.println("\n \n**MEMORY DETAILS  ** \n");
            // Print initial memory usage.
            runtime = Runtime.getRuntime();
            printUsage(runtime);

            // Allocate a 1 Megabyte and print memory usage
            bytes = new byte[1024*1024];
            printUsage(runtime);

            bytes = null;
            // Invoke garbage collector to reclaim the allocated memory.
            runtime.gc();

            // Wait 5 seconds to give garbage collector a chance to run
            try {
            Thread.sleep(5000);
            } catch(InterruptedException e) {
            e.printStackTrace();
            return;
            }

            // Total memory will probably be the same as the second printUsage call,
            // but the free memory should be about 1 Megabyte larger if garbage
            // collection kicked in.
            printUsage(runtime);
            for(int i = 0; i < 30; i++)
                     {
                         long start = System.nanoTime();
                        // log(start);
                        //number of available processors;
                         int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
                         Random random = new Random(start);
                         int seed = Math.abs(random.nextInt());
                         log("\n \n CPU USAGE DETAILS \n\n");
                         log("Starting Test with " + cpuCount + " CPUs and random number:" + seed);
                         int primes = 10000;
                         //
                         long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
                         start = System.nanoTime();
                         while(primes != 0)
                         {
                            if(isPrime(seed))
                            {
                                primes--;
                            }
                            seed++;

                        }
                         float cpuPercent = calcCPU(startCPUTime, start, cpuCount);
                         log("CPU USAGE : " + cpuPercent + " % ");


                         try
                         {
                             Thread.sleep(1000);
                         }
                         catch (InterruptedException e) {}
        }

            try
            {
                Thread.sleep(500);
            }`enter code here`
            catch (Exception ignored) { }
        }
    }

다음 코드는 Linux(유닉스) 전용이지만 실제 프로젝트에서 작동합니다.

    private double getAverageValueByLinux() throws InterruptedException {
    try {

        long delay = 50;
        List<Double> listValues = new ArrayList<Double>();
        for (int i = 0; i < 100; i++) {
            long cput1 = getCpuT();
            Thread.sleep(delay);
            long cput2 = getCpuT();
            double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
            listValues.add(cpuproc);
        }
        listValues.remove(0);
        listValues.remove(listValues.size() - 1);
        double sum = 0.0;
        for (Double double1 : listValues) {
            sum += double1;
        }
        return sum / listValues.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }

}

private long getCpuT throws FileNotFoundException, IOException {
    BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
    String line = reader.readLine();
    Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
    Matcher m = pattern.matcher(line);

    long cpuUser = 0;
    long cpuSystem = 0;
    if (m.find()) {
        cpuUser = Long.parseLong(m.group(1));
        cpuSystem = Long.parseLong(m.group(3));
    }
    return cpuUser + cpuSystem;
}

배치 파일 "Pc.bat"을 "\mukit\processor(_Total)\% Processor Time" 이라고 입력합니다.

MProcess라는 클래스를 사용할 수 있습니다.

/** Md. Mukit Hasan* CSE-JU, 35**/java.io 를 Import 합니다.*;

퍼블릭 클래스 MP프로세서 {

public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }

}

몇 가지 문자열을 조작하면 CPU 사용률이 높아집니다.다른 태스크에도 동일한 프로세스를 사용할 수 있습니다.

--무킷 하산

    OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
    System.out.println((osBean.getCpuLoad() * 100) + "%");

수입품com.sun.management.OperatingSystemMXBean

두 번째 호출 후에만 작동하므로 osBean을 저장하고 루프를 만듭니다.

언급URL : https://stackoverflow.com/questions/47177/how-do-i-monitor-the-computers-cpu-memory-and-disk-usage-in-java

반응형