Skip to content

🎥 Make videos programmatically with React

Prefer `os.availableParallelism()` over `os.cpus().length`

Jonny Burgere825487e8057
diff --git a/packages/docs/prewarm-twoslash.ts b/packages/docs/prewarm-twoslash.ts
index edfd28a033..da92346fda 100644
--- a/packages/docs/prewarm-twoslash.ts
+++ b/packages/docs/prewarm-twoslash.ts
@@ -9,16 +9,20 @@ import {
writeFileSync,
} from 'fs';
import {createRequire} from 'module';
-import {cpus} from 'os';
+import {availableParallelism, cpus} from 'os';
import {join, resolve} from 'path';
import {Glob} from 'bun';
const DOCS_ROOT = resolve(import.meta.dirname);
const CACHE_ROOT = join(DOCS_ROOT, 'node_modules', '.cache', 'twoslash');
const WORKER_PATH = join(DOCS_ROOT, 'twoslash-worker.ts');
+const cpuCount =
+ typeof availableParallelism === 'function'
+ ? availableParallelism()
+ : cpus().length;
const NUM_WORKERS = process.env.VERCEL
- ? Math.max(1, cpus().length - 1)
- : Math.max(1, cpus().length - 2);
+ ? Math.max(1, cpuCount - 1)
+ : Math.max(1, cpuCount - 2);
const pluginDir = join(DOCS_ROOT, '..', 'docusaurus-plugin');
const pluginRequire = createRequire(join(pluginDir, 'package.json'));
diff --git a/packages/renderer/src/get-cpu-count.ts b/packages/renderer/src/get-cpu-count.ts
index 42dcd179ad..8a943efaef 100644
--- a/packages/renderer/src/get-cpu-count.ts
+++ b/packages/renderer/src/get-cpu-count.ts
@@ -3,7 +3,7 @@
// However, Node.js returns the core count of the host system (up to 96!)
import {execSync} from 'node:child_process';
-import {cpus} from 'node:os';
+import {availableParallelism, cpus} from 'node:os';
let nprocCount: number | null | undefined;
@@ -25,8 +25,18 @@ export const getConcurrencyFromNProc = (): number | null => {
}
};
+const getNodeCpuCount = (): number => {
+ // os.availableParallelism() is faster and respects cgroup CPU limits in containers.
+ // Available since Node 18.14 / 19.4.
+ if (typeof availableParallelism === 'function') {
+ return availableParallelism();
+ }
+
+ return cpus().length;
+};
+
export const getCpuCount = () => {
- const node = cpus().length;
+ const node = getNodeCpuCount();
const nproc = getConcurrencyFromNProc();
if (nproc === null) {
return node;