Skip to content

Commit

Permalink
Improve minResolution
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Aug 25, 2019
1 parent 049c239 commit fa92d4e
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions src/resolution.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,42 @@ export const getTimeResolution = function() {
)
}

// Run `now()` several times in a row
// Run `now()` several times in a row.
// We do it several times because there is a chance that the next resolution
// would be hit otherwise. For example:
// - if resolution is 1ns, samples might (by chance) all be modulo 5ns
// - if resolution is 5ns, samples might (by chance) all be modulo 10ns
// The probability for this to happen is:
// - if resolution is *1ns, `1 / 5 ** length`
// - if resolution is *5ns, `1 / 2 ** length`
// So with `length` `100`, we get this error only once every `1e30` calls.
// We must use imperative code because the loop size is unknown.
/* eslint-disable fp/no-let, fp/no-loops, fp/no-mutation, fp/no-mutating-methods,
max-depth */
const getTimes = function(length) {
const times = Array.from({ length }, now)
const uniqueTimes = [...new Set(times)]
return uniqueTimes
const times = []
let lastTime = 0

while (times.length < length) {
const time = now()

// If the resolution is very low, we need to perform `now()` several times
// until the result changes
if (time !== lastTime) {
lastTime = time
times.push(time)
}
}

return times
}
/* eslint-enable fp/no-let, fp/no-loops, fp/no-mutation, fp/no-mutating-methods,
max-depth */

const REPEAT = 1e2

// Check among all `now()` if they fit a specific time resolution
const isTimeResolution = function(resolution, times) {
// Performance optimization. Avoid looping over every `times`
if (resolution === MIN_RESOLUTION) {
return true
}

return times.every(time => time % resolution === 0)
}

Expand All @@ -51,6 +71,3 @@ const getPossibleResolution = function(exponent) {
}

const POSSIBLE_RESOLUTIONS = getPossibleResolutions()

// 1 nanosecond
const MIN_RESOLUTION = POSSIBLE_RESOLUTIONS[POSSIBLE_RESOLUTIONS.length - 1]

0 comments on commit fa92d4e

Please sign in to comment.