-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
loopbench.js
47 lines (34 loc) · 970 Bytes
/
loopbench.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict'
const EE = require('events').EventEmitter
const defaults = {
limit: 42,
sampleInterval: 5
}
function loopbench (opts) {
opts = Object.assign({}, defaults, opts)
const timer = setInterval(checkLoopDelay, opts.sampleInterval)
timer.unref()
const result = new EE()
result.delay = 0
result.sampleInterval = opts.sampleInterval
result.limit = opts.limit
result.stop = clearInterval.bind(null, timer)
let last = now()
return result
function checkLoopDelay () {
const toCheck = now()
const overLimit = result.overLimit
result.delay = Number(toCheck - last - BigInt(result.sampleInterval))
last = toCheck
result.overLimit = result.delay > result.limit
if (overLimit && !result.overLimit) {
result.emit('unload')
} else if (!overLimit && result.overLimit) {
result.emit('load')
}
}
function now () {
return process.hrtime.bigint() / 1000000n
}
}
module.exports = loopbench