安装
bun add @evan/concurrency
npm install @evan/concurrency
限制
控制同步任务的同步执行.
import { Limiter } from '@evan/concurrency';
const queue = Limiter(5);
queue.add(() => new Promise(...));
queue.add(() => new Promise(...));
// wait for all promises to finish
await queue.flush();
API 参考
限制(n,选项)
创建新的限制实例.
参数:
n(数目):环缓冲器的大小options(对象):可选配置limit(数字,默认值:n):最大任务数(环+逃脱)timeout(null qq数字, 默认: 无效): 超时以毫秒计, 在超时任务被越出以释放环位后threshold(数目,默认值:0.75):慢出/超时任务切换为逃出策略的阈值比
方法
冲号( )
等待所有环任务完成.
添加(fn)
将任务添加到执行环中.
fn: 返回承诺的函数
(注:fn必须是aync并处理自己的错误)
细小版本
只有简化的环缓冲程序可以执行。 这种轻量级的版本被优化为大小(~120字节已分解),同时保持了对完成时间没有巨大差异的任务的巨大性能.
import { Limiterr } from '@evan/concurrency';
const c = new Limiterr(5);
c(async () => {});
业绩
限制器(n)使用环缓冲器和阁相器来高效地进行任务调度. 阈值选项通过基于负载的不同策略之间的切换,自动优化性能.
clk: ~3.37 GHz
cpu: Apple M2 Pro
runtime: node 23.4.0 (arm64-darwin)
benchmark avg (min … max) p75 p99 (min … top 1%)
------------------------------------------- -------------------------------
Limiter(1) 169.36 µs/iter 166.38 µs █▃
(155.75 µs … 571.08 µs) 289.17 µs ██▆▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▁▁
5.37 ipc ( 2.43% stalls) 99.52% L1 data cache
592.77k cycles 3.19M instructions 45.58% retired LD/ST ( 1.45M)
Limiter(8) 167.56 µs/iter 164.92 µs █▃
(154.83 µs … 385.50 µs) 286.46 µs ██▆▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▂▁
5.43 ipc ( 3.56% stalls) 99.08% L1 data cache
584.58k cycles 3.17M instructions 45.63% retired LD/ST ( 1.45M)
Limiter(12) 164.93 µs/iter 162.50 µs █▂
(152.38 µs … 353.04 µs) 279.67 µs ██▇▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▂▁
5.51 ipc ( 3.54% stalls) 99.09% L1 data cache
575.28k cycles 3.17M instructions 45.63% retired LD/ST ( 1.45M)
p-limit(1) 430.61 µs/iter 420.13 µs █▂
(387.38 µs … 770.88 µs) 602.21 µs ▃██▄▂▁▁▁▁▁▁▁▁▁▃▃▂▁▁▁▁
4.83 ipc ( 4.20% stalls) 97.39% L1 data cache
1.49M cycles 7.21M instructions 45.45% retired LD/ST ( 3.28M)
p-limit(8) 417.55 µs/iter 405.21 µs █▃
(379.13 µs … 713.92 µs) 563.21 µs ███▅▂▁▁▁▁▁▁▁▁▁▁▁▂▄▃▂▁
4.95 ipc ( 4.58% stalls) 97.24% L1 data cache
1.45M cycles 7.18M instructions 45.47% retired LD/ST ( 3.27M)
p-limit(12) 422.99 µs/iter 403.50 µs █
(377.42 µs … 722.46 µs) 611.46 µs ██▇▃▁▁▁▁▁▁▁▁▁▁▁▁▂▃▂▂▁
4.98 ipc ( 4.57% stalls) 97.26% L1 data cache
1.44M cycles 7.15M instructions 45.31% retired LD/ST ( 3.24M)
┌ ┐
┌┬ ╷
Limiter($c) ││───────────┤
└┴ ╵
╷┌───┬ ╷
p-limit($c) ├┤ │─────────────────┤
╵└───┴ ╵
└ ┘
152.38 µs 381.92 µs 611.46 µs
summary
Limiter($c)
+2.54…+2.53x faster than p-limit($c)
许可证
麻省理工学院 伊凡在这里