简体   繁体   English

在 Java 中查找内核数

[英]Finding Number of Cores in Java

如何从 Java 代码中找到我的应用程序可用的内核数量?

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

如果cores数少于 1,则要么您的处理器即将死亡,要么您的 JVM 中存在严重错误,要么整个世界即将崩溃。

If you want to get number of physical cores you can run cmd and terminal command and then to parse the output to get info you need.Below is shown function that returns number of physical cores .如果您想获取物理内核数,您可以运行 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 class: 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";
    }
}

} }

This is an additional way to find out the number of CPU cores (and a lot of other information), but this code requires an additional dependence:这是找出 CPU 核心数(以及许多其他信息)的额外方法,但此代码需要额外的依赖:

Native Operating System and Hardware Information https://github.com/oshi/oshi本机操作系统和硬件信息https://github.com/oshi/oshi

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

Get the number of logical CPUs available for processing:获取可用于处理的逻辑 CPU 数量:

centralProcessor.getLogicalProcessorCount();

If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.如果你想检查你机器上的核心数量,你的java程序给你的数量。

In Linux terminal: lscpu在 Linux 终端中: lscpu

In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%在 Windows 终端 (cmd) 中: echo %NUMBER_OF_PROCESSORS%

In Mac terminal: sysctl -n hw.ncpu在 Mac 终端中: sysctl -n hw.ncpu

public class CPUCores {
  public static void main(String[] args) {
    int processors = Runtime.getRuntime().availableProcessors();
    System.out.println("CPU cores: " + processors);
  }
}

Output CPU cores: 8 输出CPU内核:8

Note that this number is the total number of cores available for your Java application. 请注意,此数字是可用于Java应用程序的内核总数。

References Java Doc API 参考Java Doc API

Hyper-threading 超线程

这适用于安装了 Cygwin 的 Windows:

System.getenv("NUMBER_OF_PROCESSORS")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM