Strange behavior with process.hrtime ()

If I execute this code:

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

Result:

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

It can't be right ... arithmetic should be faster. So I will uncomment these lines to see:

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

And the results now look accurate.

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

Then I comment on these lines and get the same funny results.

What can happen? Am I missing something about process.hrtime ()?

 $ node -v v0.10.0 

Edit: I just checked this with v0.8.11 and got the same behavior.

+4
source share
1 answer

Running test cases individually returns these results:

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

These results are pretty consistent between runs, so I think your initial assumption that the arithmetic method should be faster is actually incorrect ( EDIT:) , the reason is that it is using parseInt() ).

The reason you get different results with console.log between them is caused by console.log . Probably,

+1
source

All Articles