Skip to content

Commit 35eb144

Browse files
authored
fix: implement support to timers to workers
1 parent cad6bfa commit 35eb144

3 files changed

Lines changed: 31 additions & 3 deletions

File tree

examples/worker-threads/node.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,12 @@ suite
1111
.add('Using import with node: prefix', function () {
1212
return import('node:fs');
1313
})
14+
.add('async test', async function (timer) {
15+
timer.start();
16+
let i = 0;
17+
while (i++ < timer.count) {
18+
await import("node:fs");
19+
}
20+
timer.end(timer.count);
21+
})
1422
.run();

lib/worker-runner.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,17 @@
11
const { parentPort } = require("node:worker_threads");
22
const { runBenchmark } = require("./lifecycle");
3+
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
34

45
// Deserialize the benchmark function
56
function deserializeBenchmark(benchmark) {
6-
benchmark.fn = new Function(benchmark.fn);
7+
const { isAsync, hasArg } = benchmark;
8+
const fnPrototype = isAsync ? AsyncFunction : Function;
9+
10+
if (hasArg) {
11+
benchmark.fn = new fnPrototype("timer", benchmark.fn);
12+
} else {
13+
benchmark.fn = new fnPrototype(benchmark.fn);
14+
}
715
}
816

917
parentPort.on(

test/worker.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,27 @@ describe("Using worker_threads", () => {
2121
})
2222
.add("Import without node: prefix", () => {
2323
return import("node:fs");
24+
})
25+
.add("async test", async () => {
26+
return import("node:fs");
27+
})
28+
.add("async with timer", async (timer) => {
29+
timer.start();
30+
let i = 0;
31+
while (i++ < timer.count) {
32+
await import("node:fs");
33+
}
34+
timer.end(timer.count);
2435
});
36+
2537
await bench.run();
2638
});
2739

2840
after(() => {
2941
mock.restoreAll();
3042
});
3143

32-
it("should create a new Worker 2 times", () => {
33-
assert.strictEqual(workerThreads.Worker.mock.calls.length, 2);
44+
it("should create a new Worker 4 times", () => {
45+
assert.strictEqual(workerThreads.Worker.mock.calls.length, 4);
3446
});
3547
});

0 commit comments

Comments
 (0)