process.hrtime()的怪异行为

如果我执行这个代码:

//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 

编辑:我只testing了这个v0.8.11,并得到相同的行为。

完全分开运行testing用例返回这些结果:

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

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

中间有一个console.log ,得到不同结果的原因可能是由console.log本身引起的。