在Java中查找内核数

在Java中查找内核数,java,Java,如何从Java代码中找到应用程序可用的内核数 int cores = Runtime.getRuntime().availableProcessors(); 如果核心数小于1,则可能是处理器即将死亡,或者JVM中存在严重缺陷,或者宇宙即将爆炸。这在安装了Cygwin的Windows上有效: System.getenv(“处理器数量”)如果要获取物理内核的数量,可以运行cmd和terminal命令,然后解析输出以获取所需信息。下面显示了返回物理内核数量的函数 private int getNum

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

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

如果
核心数
小于1,则可能是处理器即将死亡,或者JVM中存在严重缺陷,或者宇宙即将爆炸。

这在安装了Cygwin的Windows上有效:


System.getenv(“处理器数量”)

如果要获取物理内核的数量,可以运行cmd和terminal命令,然后解析输出以获取所需信息。下面显示了返回物理内核数量的函数

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内核数量(以及许多其他信息)的方法,但此代码需要额外的依赖性:

本机操作系统和硬件信息

获取可用于处理的逻辑CPU的数量:

centralProcessor.getLogicalProcessorCount();

如果您想配音,请检查您机器上的内核数量与java程序提供给您的内核数量

在Linux终端中:
lscpu

在Windows终端(cmd)中:
echo%处理器数量%


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

几乎所有的意图和目的都是“core==处理器”。使用纯Java很难找到机器实际拥有的内核数。使用Runtime.getRuntime().availableProcessors()可以很容易地找到Java程序在启动时可以使用的内核数。由于所有主要的现代操作系统都能够设置CPU亲和力(即,将应用程序限制在一定数量的内核上),这是一个需要注意的问题。逻辑内核还是物理内核?这里有一个重要的区别。另请参见:这将为您提供逻辑线程的数量。e、 g.如果你打开了超线程,这将是内核数量的两倍。@Peter,是的,说得对。当我用我的i7机器执行这个动作时,我感觉自己成了山中之王!:)@Peter Lawrey:它只给出JVM实际可用的逻辑线程的数量(我猜是在启动时)。使用CPU亲和力,用户/操作系统可以限制JVM看到的“核心”数量。您甚至可以在运行的JVM上执行此操作,但我不太确定这会如何影响availableProcessors()。@PeterLawrey:availableProcessors()的Java文档说,这似乎不正确“在虚拟机的特定调用过程中,此值可能会更改。因此,对可用处理器数量敏感的应用程序应偶尔轮询此属性并适当调整其资源使用情况。“@universe爆炸之类的:或者机器实际有超过2147483647个逻辑线程可用?;)这是一段很好的面向对象代码。:)OSValidator类支持OSX,但getNumberOfCores完全忽略它。顺便说一句,“Mac”应该在您的isUnix()中,但是。。。对于BSD、OSX,不存在lscpu命令,您的getNumberOfCores将返回0。在Linux上,您必须通过“socket(s)”将“Core(s)”乘以“socket(s)”。另外,我会使用正则表达式。最好使用“OS.contains()”而不是“OS.indexOf()”。它提高了可读性,减少了输入。我安装了Cygwin,但它可以在Windows shell中运行:
groovy-e“println System.getenv('NUMBER OF_PROCESSORS')”
我不知道这是否是一个标准的Windows环境变量,但是:
set NUMBER OF_处理器
可以从Windows命令行为我工作。这还可以让您使用centralProcessor.getPhysicalProcessorCount(),这可能是目前java中获取该信息的最佳方式。如果您的线程几乎总是有工作要做,并且您想知道在为其他线程和进程留下定义良好的剩余CPU容量的同时可以启动的线程数,那么这就是计算应该基于的数量。
centralProcessor.getLogicalProcessorCount();