4

如果我执行此代码:

//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 测试了这个并得到了同样的行为。

4

1 回答 1

2

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

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

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

你得到不同结果的原因可能是它本身console.log造成的。console.log

于 2013-03-18T17:45:54.720 回答