Count to 1B in Ruby, Python, R, JavaScript and C++
github.com
github.com
Edit: discussed previously https://news.ycombinator.com/item?id=35398298
That makes it less likely that a compiler optimizes this, but doesn’t guarantee it won’t do it (it is fairly easy to prove how often the loop runs and what the value of n is afterwards)
Edit: for getting an idea about what compilers can do, read https://kristerw.blogspot.com/2019/04/how-llvm-optimizes-geo... for examples of what LLVM (the backend of various language implementations, including clang) does.
c++ 1.129 seconds
python 41.674 seconds
ruby 8.730 seconds
R 13.602 seconds
js (node) 0.481 seconds
What surprises me: Python slower than R and ruby. js faster than c++.
Nowadays Ruby includes a JIT compiler.
g++ -std=c++14 1bn.cpp
time ./a.out
1000000000
When I run this on a Macbook Air M2 without optimizations versus with “-O3”, wall clock running time decreases from about 700ms to 6 ms (sometimes less than that)(Also, with “-O3”, changing the loop limit doesn’t affect running time, so clang optimizes away that loop)