Skip to content

Commit

Permalink
feat: physical cores
Browse files Browse the repository at this point in the history
  • Loading branch information
Aslemammad committed Jan 3, 2022
1 parent e384b10 commit 85887e1
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -44,7 +44,7 @@ declare global {
}
}

const cpuCount: number = cpus().length
const cpuCount: number = physicalCpuCount

interface AbortSignalEventTargetAddOptions {
once: boolean
Expand Down
48 changes: 48 additions & 0 deletions src/physicalCpuCount.ts
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 85887e1

Please sign in to comment.