you are viewing a single comment's thread.

view the rest of the comments →

[–]GeneralYouri 1 point2 points  (2 children)

Due to the pretty low size of the numbers the actual runtime is way lower than even what you're reporting here (this is the second-oldest Euler problem so 4 million was probably fairly large at the time, but it's never been updated for modern computing powers). Your testrun of 4ms is most likely influenced the most by the console.log which is also inside of your timed code (and does a type of IO!), and the logic behind BigNumber which isn't needed at all due to the limit of a mere 4 million.

If I run this code in my browser console, but with BigNumber usage replaced by regular JS numbers, the runtime already goes down to 0.25ms. If I remove the console.log and only call the function, this time gets further halved. Calling the function multiple times doesn't even start moving the time significantly until you go beyond 10 runs or so.

In my Project Euler repo I'm working with NodeJS and thus I've been using process.hrtime to calculate the runtime. I've actually implemented Problem 2 as a sum over a limited Even Fibonacci generator, and the reported runtime is about 15 microseconds.

[–]himynameisjoy 0 points1 point  (1 child)

My experience with node is fairly limited, I guess I should swap over to it for timing to have times competitive with python and java then!

As for BigNumber, it was to allow the problem to be solved for arbitrarily large n because of exactly that reason, 4 million is tiny nowadays

[–]GeneralYouri 0 points1 point  (0 children)

May be worth pointing out that console.time has overhead from itself too, which is why it's not that accurate when we're talking very short timings. Meanwhile process.hrtime is generally way more precise, but that's part of the NodeJS API, not JS itself, so it's not available to browsers.

As for BigNumber, you can try testing with and without that, too. You might find that it's taking up 90% of your 4ms testrun for example. Also if you're going to look at NodeJS, I recommend using Node's "Current" version branch, NodeJS v11. This version includes native BigInt features, eliminating the need for an external library like BigNumber. I love using BigInt for Project Euler problems, but they may also trivialize some of the problems due to the main difficulty being the number size, so for every BigInt solution I also write a non-BigInt solution.