import java.io.*;
class Test {
static private boolean isWindows = System.getProperty("os.name").startsWith("Windows");
static private int n_CPUs = 0;
static public int getCPUCount() {
if (n_CPUs > 0) return n_CPUs;
if (isWindows) return 1; // no clue
// POSIX systems, attempt to count CPUs from /proc/stat
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cat /proc/stat");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
n_CPUs = 0;
// valid cores will print as cpu0, cpu1. cpu2 ...
while ((line = br.readLine()) != null) {
if (0 == line.indexOf("cpu") && line.length() > 3
&& Character.isDigit(line.charAt(3))) {
n_CPUs++;
}
}
// fix possible errors
if (0 == n_CPUs) n_CPUs = 1;
return n_CPUs;
} catch (Exception e) {
//Utils.log(e.toString()); // just one line
return 1;
}
}
public static void main(String args[]) {
System.out.println("No of CPU = "+getCPUCount());
}
}
No comments:
Post a Comment