-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
cpuCount.js
67 lines (58 loc) 路 1.47 KB
/
cpuCount.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// @flow
import os from 'os';
import {execSync} from 'child_process';
const exec = (command: string): string => {
try {
let stdout = execSync(command, {
encoding: 'utf8',
// This prevents the command from outputting to the console
stdio: [null, null, null],
});
return stdout.trim();
} catch (e) {
return '';
}
};
export function detectRealCores(): number {
let platform = os.platform();
let amount = 0;
if (platform === 'linux') {
amount = parseInt(
exec('lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l'),
10,
);
} else if (platform === 'darwin') {
amount = parseInt(exec('sysctl -n hw.physicalcpu_max'), 10);
} else if (platform === 'win32') {
const str = exec('wmic cpu get NumberOfCores').match(/\d+/g);
if (str !== null) {
amount = parseInt(str.filter(n => n !== '')[0], 10);
}
}
if (!amount || amount <= 0) {
throw new Error('Could not detect cpu count!');
}
return amount;
}
let cores;
export default function getCores(bypassCache?: boolean = false): number {
// Do not re-run commands if we already have the count...
if (cores && !bypassCache) {
return cores;
}
try {
cores = detectRealCores();
} catch (e) {
// Guess the amount of real cores
cores = os
.cpus()
.filter(
(cpu, index) => !cpu.model.includes('Intel') || index % 2 === 1,
).length;
}
// Another fallback
if (!cores) {
cores = 1;
}
return cores;
}