process.hrtime()的奇怪行为

时间:2013-03-18 09:04:16

标签: node.js

如果我执行此代码:

//brute force
console.log('------------------');
console.log('Brute Force Method');
console.log('------------------');
var aTimer = process.hrtime();
var sum = 0;
for (var x = 3 ; x < 1000 ; x++) {
  if (x % 3 === 0 || x % 5 === 0) {
    sum += x;
  }
}
console.log('The sum of them is: '+ sum);
//console.log(aTimer);
var aTimerDiff = process.hrtime(aTimer);
console.log('Benchmark took %d nanoseconds.', aTimerDiff[0] * 1e9 + aTimerDiff[1]);

//arithmetic method
console.log('------------------');
console.log('Arithmetic Method');
console.log('------------------');
var bTimer = process.hrtime();
var term3 = parseInt(999/3);
var threes = 3 * term3 * (term3 + 1) / 2;
var term5 = parseInt(999/5);
var fives = 5 * term5 * (term5 + 1) / 2;
var term15 = parseInt(999/15);
var fifteens = 15 * term15 * (term15 + 1) / 2;
console.log('The sum of them is: '+ (threes + fives - fifteens));
//console.log(bTimer);
var bTimerDiff = process.hrtime(bTimer);
console.log('Benchmark took %d nanoseconds.', bTimerDiff[0] * 1e9 + bTimerDiff[1]);

console.log('------------------');
console.log('Which is Faster');
console.log('------------------');
if (bTimerNano > aTimerNano) {
  console.log('A is %d nanoseconds faster than B.', bTimerNano - aTimerNano)
}
else {
  console.log('B is %d nanoseconds faster than A.', aTimerNano - bTimerNano)
}

结果是:

------------------
Brute Force Method
------------------
The sum of them is: 233168
Benchmark took 64539 nanoseconds.
------------------
Arithmetic Method
------------------
The sum of them is: 233168
Benchmark took 155719 nanoseconds.
------------------
Which is Faster
------------------
A is 91180 nanoseconds faster than B.

这不可能......算术应该更快。所以我取消注释这些行来看看:

console.log(aTimer);
console.log(bTimer);

结果现在看起来很准确。

------------------
Brute Force Method
------------------
The sum of them is: 233168
[ 1697962, 721676140 ]
Benchmark took 1642444 nanoseconds.
------------------
Arithmetic Method
------------------
The sum of them is: 233168
[ 1697962, 723573374 ]
Benchmark took 284646 nanoseconds.
------------------
Which is Faster
------------------
B is 1357798 nanoseconds faster than A.

然后我再次评论这些线条,我得到了同样的时髦结果。

可能导致这种情况发生的原因是什么?我错过了关于process.hrtime()的内容吗?

$ node -v
v0.10.0

编辑:我刚用v0.8.11对此进行了测试并得到了同样的行为。

1 个答案:

答案 0 :(得分:2)

完全单独运行测试用例会返回以下结果:

Brute Force:       [ 0, 32414 ]
Arithmetic Method: [ 0, 123523 ]

这些结果在运行之间非常一致,所以我认为你的算术方法应该更快的初始假设实际上是错误的(编辑:其原因似乎是使用parseInt())。

中间因console.log而获得不同结果的原因可能是console.log本身造成的。