node-sleep
node-sleep copied to clipboard
usleep deviation was too large
1 sec =1,000 millisec=1,000,000 microsec=1,000,000,000 nanosec
I have a code like this:
start = get_start_time();
usleep(100000); // sleep 100000 microsecond (or 100 millisecond).
end = get_end_time();
diff = end - start;
assert(80000 < diff && diff < 120000); // I think the deviation should be (-20%, 20%).
This code always runs successfully on my own computer (Linux, Windows and Mac). On travis-CI, it only succeeded on Linux and Windows, but not on Mac. The test code is here, and the CI result is here.
Why failed on MacOS? Are there any issues with the clock of Mac virtual machine?
To be honest I have no experience with Mac virtual machines so I don't know. I do know that travis runs multiple tests on the same machines so they might sometimes be slower or faster. This is why it's a broad range of deviations that are already allowed.
Looks like the pull request you made (https://github.com/erikdubbelboer/node-sleep/pull/102) ran fine so it doesn't always fail. If you restart your job it might also succeed this time?
The travis-CI always fails in my fork project of node-sleep
, I think the reason is that I added two test cases in test.js
. In these two test cases, I used process.hrtime()
(more accurate then Date()
) to measure the time.
I have just made a pull request where I switch all timing code to use process.hrtime()
: https://github.com/erikdubbelboer/node-sleep/pull/103
Here everything seems to be working fine: https://travis-ci.org/erikdubbelboer/node-sleep/builds/630569802?utm_source=github_status&utm_medium=notification
My guess is 100 milliseconds is just too little for a virtual machine on a server that is probably busy doing other things as well (travis servers are probably very busy). The VM not getting the CPU for 100ms is maybe very likely.
Any virtual machine can have extensive time variation, this is core to virtualization design and function. The recommendation from Microsoft for Hyper-V, from VMware for ESXi, etc., is that if you have time critical requirements, you either don't use virtual machines, or you make sure the virtual machines have assigned resources as needed. All virtual machines exhibit time stretching issues.