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)
}
The result is:
------------------
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.
That can't be right... arithmetic should be faster. So I uncomment these lines to get a look:
console.log(aTimer);
console.log(bTimer);
And the results look accurate now.
------------------
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 those lines out again and I get the same funky results.
What could cause this to happen? Am I missing something about process.hrtime()?
$ node -v
v0.10.0
Edit: I just tested this with v0.8.11 and get the same kind of behavior.
Running the test cases completely separately returns these results:
Brute Force: [ 0, 32414 ]
Arithmetic Method: [ 0, 123523 ]
Those results are pretty consistent between runs, so I'm thinking that your initial assumption that the arithmetic method should be faster is actually wrong (EDIT: the reason for that seems to be the use of parseInt()).
The reason you get different results with a console.log in between is caused by that console.log itself probably.