I just found out the other day that Node.js has a high resolution timer function called
This timer supposedly has nanosecond resolution, which is fantastic because now I can time stuff to a much greater accuracy than I could with the Date module.
Anyways I'm using this new timer to try and make a Timer object that can time different tasks passed to it. Unfortunately, I'm getting some strange negative results that make me question the accuracy and reliability of this supposed "high res" timer.
Let me show you my code:
hrTimer.js
//IMPORTS
var async = require('async');
HrTimer = {
time: function(task) {
var t1 = t2 = '';
async.series([
function(callback){
t1 = process.hrtime();
callback();
},
task,
function(callback){
t2 = process.hrtime();
callback();
}
]);
var t1 = t1[0].toString() + '.' + t1[1].toString();
var t2 = t2[0].toString() + '.' + t2[1].toString();
var dif = parseFloat(t2)-parseFloat(t1);
if(dif < 0){
debugger;
console.log(t1);
console.log(t2);
}
return dif;
}
};
module.exports = HrTimer;
So sometimes it will enter the code block where dif < 0. This shouldn't happen provided the async module is working properly, and the timer is working properly. Any help?
The values you are processing are not floats! You cannot just append the values to get a float value. For instance if the time is 1 second and 1 nanosecond, the float value would be 1.000000001, not 1.1. Also, hrtime can take an argument to find the difference between two values.
You need to process the value like this:
var t2 = process.hrtime(t1);
That will return the values in an array as you know. I'd recommend just using the array value.
That said, what you have will also not work asynchronously, so either ditch the async.series call and just do this:
var t1 = process.hrtime();
task();
return process.hrtime(t1);
or implement it asynchronously:
time: function(task, doneCb) {
var t1 = process.hrtime();
task(function(){
doneCb(process.hrtime(t1));
});
}