fastcar-workerpool
v0.0.2
Published
工作线程方法包装
Downloads
3
Readme
工作线程包装
快速安装
npm install fastcar-workerpool
使用场景
针对于cpu密集型的操作进行批量计算时提高对cpu的利用率
使用示例
import {WorkerPool} from "fastcar-workerpool";
const total = 10000; //计算阶乘一直到一万次
//求阶乘的方法
function factorial(num: number): number {
if (num <= 2) {
return num;
}
return num * factorial(num - 1);
}
let scripts = require.resolve("./WorkerScripts");
describe("工作线程池-阶乘测试", () => {
it("多线程耗时动态传递函数测试", () => {
let workerPool = new WorkerPool(4);
let finshed = 0;
let startTime = Date.now();
for (let i = 0; i < total; i++) {
workerPool.runTask({
task: factorial,
args: [i],
cb: (err: Error, res: number) => {
finshed++;
if (finshed == total) {
console.log("任务完成耗时:", Date.now() - startTime);
queueMicrotask(() => {
workerPool.close();
});
}
},
});
}
});
it("多线程初始化脚本测试", () => {
let workerPool = new WorkerPool(4, "", {
scripts: [factorial.toString()],
});
let finshed = 0;
let startTime = Date.now();
for (let i = 0; i < total; i++) {
workerPool.runTask({
args: [i],
cb: (err: Error, res: number) => {
finshed++;
if (finshed == total) {
console.log("任务完成耗时:", Date.now() - startTime);
queueMicrotask(() => {
workerPool.close();
});
}
},
});
}
});
it("多线程自定义脚本测试", () => {
let workerPool = new WorkerPool(4, scripts);
let finshed = 0;
let startTime = Date.now();
for (let i = 0; i < total; i++) {
workerPool.runTask({
args: [i],
cb: (err: Error, res: number) => {
finshed++;
if (finshed == total) {
console.log("任务完成耗时:", Date.now() - startTime);
queueMicrotask(() => {
workerPool.close();
});
}
},
});
}
});
});