programing

Java에서 코어 수 찾기

prostudy 2022. 5. 6. 19:44
반응형

Java에서 코어 수 찾기

Java 코드 내에서 애플리케이션에 사용할 수 있는 코어 수를 찾으려면 어떻게 해야 하는가?

int cores = Runtime.getRuntime().availableProcessors();

만약cores프로세서가 곧 죽거나 JVM에 심각한 버그가 있거나 우주가 폭발할 경우

물리적 코어 수를 얻으려면 cmd와 터미널 명령을 실행한 다음 출력을 구문 분석하여 필요한 정보를 얻으십시오.물리적 코어 수를 반환하는 기능은 아래와 같다.

private int getNumberOfCPUCores() {
    OSValidator osValidator = new OSValidator();
    String command = "";
    if(osValidator.isMac()){
        command = "sysctl -n machdep.cpu.core_count";
    }else if(osValidator.isUnix()){
        command = "lscpu";
    }else if(osValidator.isWindows()){
        command = "cmd /C WMIC CPU Get /Format:List";
    }
    Process process = null;
    int numberOfCores = 0;
    int sockets = 0;
    try {
        if(osValidator.isMac()){
            String[] cmd = { "/bin/sh", "-c", command};
            process = Runtime.getRuntime().exec(cmd);
        }else{
            process = Runtime.getRuntime().exec(command);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    String line;

    try {
        while ((line = reader.readLine()) != null) {
            if(osValidator.isMac()){
                numberOfCores = line.length() > 0 ? Integer.parseInt(line) : 0;
            }else if (osValidator.isUnix()) {
                if (line.contains("Core(s) per socket:")) {
                    numberOfCores = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
                }
                if(line.contains("Socket(s):")){
                    sockets = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
                }
            } else if (osValidator.isWindows()) {
                if (line.contains("NumberOfCores")) {
                    numberOfCores = Integer.parseInt(line.split("=")[1]);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(osValidator.isUnix()){
        return numberOfCores * sockets;
    }
    return numberOfCores;
}

OSValidator 클래스:

public class OSValidator {

private static String OS = System.getProperty("os.name").toLowerCase();

public static void main(String[] args) {

    System.out.println(OS);

    if (isWindows()) {
        System.out.println("This is Windows");
    } else if (isMac()) {
        System.out.println("This is Mac");
    } else if (isUnix()) {
        System.out.println("This is Unix or Linux");
    } else if (isSolaris()) {
        System.out.println("This is Solaris");
    } else {
        System.out.println("Your OS is not support!!");
    }
}

public static boolean isWindows() {
    return (OS.indexOf("win") >= 0);
}

public static boolean isMac() {
    return (OS.indexOf("mac") >= 0);
}

public static boolean isUnix() {
    return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
}

public static boolean isSolaris() {
    return (OS.indexOf("sunos") >= 0);
}
public static String getOS(){
    if (isWindows()) {
        return "win";
    } else if (isMac()) {
        return "osx";
    } else if (isUnix()) {
        return "uni";
    } else if (isSolaris()) {
        return "sol";
    } else {
        return "err";
    }
}

}

이는 CPU 코어 수(및 기타 많은 정보)를 알아내기 위한 추가적인 방법이지만, 이 코드는 추가적인 의존성을 필요로 한다.

기본 운영 체제 및 하드웨어 정보 https://github.com/oshi/oshi

SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();

처리할 수 있는 논리 CPU 수 가져오기:

centralProcessor.getLogicalProcessorCount();

만약 당신이 당신의 컴퓨터에 당신이 가지고 있는 코어의 양을 당신의 Java 프로그램이 당신에게 주는 숫자에 더빙하기를 원한다면.

Linux 터미널의 경우:lscpu

Windows 터미널(cmd): echo %NUMBER_OF_PROCESSORS%

Mac 터미널의 경우:sysctl -n hw.ncpu

이 기능은 Windows(윈도우)에서 Cygwin이 설치된 경우:

System.getenv("NUMBER_OF_PROCESSORS")

참조URL: https://stackoverflow.com/questions/4759570/finding-number-of-cores-in-java

반응형