From 51474716e986601b354cb0be638f68d6100de275 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 1 Jul 2023 12:09:39 +0200 Subject: [PATCH] feat: add safe helper around os.availableParallelism MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/index.ts | 1 + src/utils.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/index.ts b/src/index.ts index 367c205c..9bd8bbf9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -65,3 +65,4 @@ export type { } from './utility-types' export type { CircularArray } from './circular-array' export type { Queue } from './queue' +export { availableParallelism } from './utils' diff --git a/src/utils.ts b/src/utils.ts index c7efbc22..a6f5fbcc 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,4 @@ +import os from 'node:os' import type { MeasurementStatisticsRequirements, WorkerChoiceStrategyOptions @@ -30,6 +31,22 @@ export const DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS: MeasurementStatisticsR median: false } +/** + * Safe helper to get the host OS optimized maximum pool size. + */ +export const availableParallelism = (): number => { + let availableParallelism = 1 + try { + availableParallelism = os.availableParallelism() + } catch { + const cpus = os.cpus() + if (Array.isArray(cpus) && cpus.length > 0) { + availableParallelism = cpus.length + } + } + return availableParallelism +} + /** * Compute the median of the given data set. * -- 2.34.1