Skip to content

Instantly share code, notes, and snippets.

@bjouhier
Last active April 3, 2017 18:48
Show Gist options
  • Save bjouhier/c7adb5f54caf9fc86d6e to your computer and use it in GitHub Desktop.
Save bjouhier/c7adb5f54caf9fc86d6e to your computer and use it in GitHub Desktop.
timedrift.js
"use strict";
function millis(hr) {
return hr[0] * 1000 + Math.floor(hr[1] / 1000000);
}
function busyWait(ms, cb) {
var hr0 = process.hrtime();
while (millis(process.hrtime(hr0)) < ms);
var elapsed = millis(process.hrtime(hr0));
console.log("busy:\texpected " + ms + ", got " + elapsed);
cb();
}
function idleWait(ms, cb) {
var hr0 = process.hrtime();
setTimeout(function() {
var elapsed = millis(process.hrtime(hr0));
console.log("idle:\texpected " + ms + ", got " + elapsed + //
(elapsed > ms + 100 ? " SURPRISE!!" : ""));
cb();
}, ms);
}
function combined(a) {
busyWait(300, function() {
idleWait(100,function(){
a < 50 && combined(++a);
});
});
}
combined(0);
@bjouhier
Copy link
Author

bjouhier commented Aug 7, 2014

Output:

busy:   expected 300, got 300
idle:   expected 100, got 102
busy:   expected 300, got 300
idle:   expected 100, got 402 SURPRISE!!
busy:   expected 300, got 300
idle:   expected 100, got 401 SURPRISE!!
busy:   expected 300, got 300
idle:   expected 100, got 401 SURPRISE!!
DONE: 2516

@bjouhier
Copy link
Author

bjouhier commented Aug 8, 2014

I update to measure times with process.hrtime rather than Date.now. Same results

@natbro
Copy link

natbro commented Dec 5, 2014

the fact that you get a drift exactly equal to the amount of time you sleep/idle looks suspiciously like the error i get using chained setTimeout()'s. if you want to read my gist, you'll see somehow using clearTimeout() eradicates the drift. https://gist.github.com/natbro/bf872ac473a1bba04008

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment