有没有办法在Java中获取有关CPU模型(用于UNIX系统)的信息?我的意思是不使用cat /proc/cpuinfo
等系统命令。
我想获得类似的东西:"英特尔(R)Xeon(R)CPU E5-2640 0 @ 2.50GHz"
谢谢!
我认为这个问题是此问题的副词,但是我将重新提出最佳答案。
您可以从运行时类获得一些有限的内存信息。它 真的不是您想要的,但我想我会 为了完整而提供它。这是一个小例子。你 还可以从java.io.file类获取磁盘使用信息。这 磁盘空间用法需要Java 1.6或更高。
public class Main { public static void main(String[] args) { /* Total number of processors or cores available to the JVM */ System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory)); /* Total memory currently available to the JVM */ System.out.println("Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root : roots) { System.out.println("File system root: " + root.getAbsolutePath()); System.out.println("Total space (bytes): " + root.getTotalSpace()); System.out.println("Free space (bytes): " + root.getFreeSpace()); System.out.println("Usable space (bytes): " + root.getUsableSpace()); } } }
在您的情况下,您想要Runtime.getRuntime().availableProcessors()
。
使用Sigar API有另一种方法。为此,您需要从此链接下载Sigar,然后检查一下将其包含在项目中如何将Sigar API包含在Java Project中。
然后,您将使用类似的东西:
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
public class CpuInfo {
public static void main(String[] args) throws SigarException {
Sigar sigar = new Sigar();
org.hyperic.sigar.CpuInfo[] cpuInfoList = sigar.getCpuInfoList();
for(org.hyperic.sigar.CpuInfo info : cpuInfoList){
System.out.println("CPU Model : " + info.getModel());
}
}
}
如果您想要该级别的细节,最好的选择是阅读/proc/cpuinfo
的内容并解析您想要的零件。
否则,从JVM中,您可以获得处理器核心数量的数量
int count = Runtime.getRuntime().availableProcessors();
或OS体系结构:
String arch = System.getProperty("os.arch");
我只需阅读 /proc/cpuinfo
。
String model = Files.lines(Paths.get("/proc/cpuinfo"))
.filter(line -> line.startsWith("model name"))
.map(line -> line.replaceAll(".*: ", ""))
.findFirst().orElse("")
似乎不再维护另一个答案中提到的sigar,并且由于64b/32b incompatibilites而无法使用最近的Windows版本(请参阅PR 142)。
似乎有另一个库是出于目的,似乎还活着(几天前出版了最后版本)oshi。
使用oshi,您可以获取这样的信息:
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
CentralProcessor cpu = hal.getProcessor();
String name = cpu.getProcessorIdentifier().getName();