feat: add safe helper around os.availableParallelism
authorJérôme Benoit <jerome.benoit@sap.com>
Sat, 1 Jul 2023 10:09:39 +0000 (12:09 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Sat, 1 Jul 2023 10:09:39 +0000 (12:09 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/index.ts
src/utils.ts

index 367c205c977582f14ea68b4f8d8776eff373581f..9bd8bbf9a7d99a755bf402e678011fed0e762314 100644 (file)
@@ -65,3 +65,4 @@ export type {
 } from './utility-types'
 export type { CircularArray } from './circular-array'
 export type { Queue } from './queue'
+export { availableParallelism } from './utils'
index c7efbc22638c59b55bd5e7508f3e19877c3c12a1..a6f5fbcc5b729b98f5dec1da1de8178eff830d40 100644 (file)
@@ -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.
  *