From 85887e196e2af6bddb026f11d3b872443820cf8d Mon Sep 17 00:00:00 2001 From: aslemammad Date: Mon, 3 Jan 2022 20:44:02 +0330 Subject: [PATCH] feat: physical cores --- README.md | 1 + src/index.ts | 4 ++-- src/physicalCpuCount.ts | 48 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/physicalCpuCount.ts diff --git a/README.md b/README.md index ba1b551..560af35 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Tinypool is a fork of piscina. What we try to achieve in this library, is to eli - ✅ Smaller install size, 36KB - ✅ Minimal - ✅ No dependencies +- ✅ Physical cores instead of Logical cores with [physical-cpu-count](https://www.npmjs.com/package/physical-cpu-count) - ❌ No utilization - ❌ No NAPI diff --git a/src/index.ts b/src/index.ts index d291f7d..68f4177 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,13 +7,13 @@ import { import { once } from 'events' import EventEmitterAsyncResource from './EventEmitterAsyncResource' import { AsyncResource } from 'async_hooks' -import { cpus } from 'os' import { fileURLToPath, URL } from 'url' import { dirname, join, resolve } from 'path' import { inspect, types } from 'util' import assert from 'assert' import { performance } from 'perf_hooks' import { readFileSync } from 'fs' +import physicalCpuCount from './physicalCpuCount' import { ReadyMessage, RequestMessage, @@ -44,7 +44,7 @@ declare global { } } -const cpuCount: number = cpus().length +const cpuCount: number = physicalCpuCount interface AbortSignalEventTargetAddOptions { once: boolean diff --git a/src/physicalCpuCount.ts b/src/physicalCpuCount.ts new file mode 100644 index 0000000..7155c70 --- /dev/null +++ b/src/physicalCpuCount.ts @@ -0,0 +1,48 @@ +// https://www.npmjs.com/package/physical-cpu-count in ESM + +import os from 'os' +import childProcess from 'child_process' + +function exec(command: string) { + const output = childProcess.execSync(command, { encoding: 'utf8' }) + return output +} + +let amount: number + +try { + const platform = os.platform() + + if (platform === 'linux') { + const output = exec('lscpu -p | egrep -v "^#" | sort -u -t, -k 2,4 | wc -l') + amount = parseInt(output.trim(), 10) + } else if (platform === 'darwin') { + const output = exec('sysctl -n hw.physicalcpu_max') + amount = parseInt(output.trim(), 10) + // @ts-ignore + } else if (platform === 'windows' || platform === 'win32') { + const output = exec('WMIC CPU Get NumberOfCores') + amount = output + .split(os.EOL) + .map(function parse(line) { + return parseInt(line) + }) + .filter(function numbers(value) { + return !isNaN(value) + }) + .reduce(function add(sum, number) { + return sum + number + }, 0) + } else { + const cores = os.cpus().filter(function (cpu, index) { + const hasHyperthreading = cpu.model.includes('Intel') + const isOdd = index % 2 === 1 + return !hasHyperthreading || isOdd + }) + amount = cores.length + } +} catch { + amount = os.cpus().length +} + +export default amount