[英]Is there a way in Java to find out how many CPUs (or cores) are installed?
I want to make some tuning for multithreaded program. 我想对多线程程序进行一些调整。
If I know how much threads can really work in parallel I can make the program much more effective. 如果我知道多少线程可以并行工作,我可以使程序更有效。
Is there a way in Java to get this info? 有没有办法在Java中获取此信息?
You can use 您可以使用
Runtime.getRuntime().availableProcessors()
But its more of a best guess and even mentioned by the API 但它更多的是最好的猜测,甚至是API提到的
This value may change during a particular invocation of the virtual machine.
在特定的虚拟机调用期间,此值可能会更改。 Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.
因此,对可用处理器数量敏感的应用程序应偶尔轮询此属性并适当调整其资源使用情况。
One note about the availableProcessors() method, it does not distinguish between physical cpus and virtual cpus. 关于availableProcessors()方法的一个注意事项,它不区分物理cpu和虚拟cpu。 eg, if you have hyperthreading enabled on your computer the number will be double the number of physical cpus (which is a little frustrating).
例如,如果您的计算机上启用了超线程,则该数字将是物理cpu的数量的两倍(这有点令人沮丧)。 unfortunately, there is no way to determine real vs. virtual cpus in pure java.
不幸的是,没有办法在纯java中确定真实与虚拟cpu。
Runtime.getRuntime().availableProcessors();
How about (code snippets speak a 1000 words): 怎么样(代码片段说1000字):
public class Main {
/**
* Displays the number of processors available in the Java Virtual Machine
*/
public void displayAvailableProcessors() {
Runtime runtime = Runtime.getRuntime();
int nrOfProcessors = runtime.availableProcessors();
System.out.println("Number of processors available to the Java Virtual Machine: " + nrOfProcessors);
}
public static void main(String[] args) {
new Main().displayAvailableProcessors();
}
}
Yes on windows for sure. 是的,确实在Windows上。 JNA with kernel32.dll.
JNA与kernel32.dll。 Use
SYSTEM_INFO
structure from GetNativeSystemInfo
call. 使用
GetNativeSystemInfo
调用的SYSTEM_INFO
结构。 There is dwNumberOfProcessors
among other things. 还有
dwNumberOfProcessors
等。
I believe this will provide the actual number of processors installed, not the number available. 我相信这将提供实际安装的处理器数量,而不是可用数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.