-
-
Save nschloe/4e1007dbcff37c5d03a77cf480c89bf4 to your computer and use it in GitHub Desktop.
import math | |
import numpy as np | |
import perfplot | |
import random | |
def plain_loop(n): | |
inside = 0 | |
random.seed() | |
for _ in range(n): | |
a = random.random() | |
b = random.random() | |
c = math.pow(a, 2.0) + math.pow(b, 2.0) | |
if c <= 1.0: | |
inside += 1 | |
return inside | |
def plain_loop2(n): | |
inside = 0 | |
random.seed() | |
for _ in range(n): | |
a = random.random() | |
b = random.random() | |
c = a * a + b * b | |
if c <= 1.0: | |
inside += 1 | |
return inside | |
def numpy(n): | |
rng = np.random.default_rng(0) | |
a, b = rng.random((2, n)) | |
c = a * a + b * b | |
inside = np.sum(c <= 1.0) | |
return inside | |
def numpy2(n): | |
rng = np.random.default_rng(0) | |
p = rng.random((2, n)) | |
c = np.einsum("ij,ij->j", p, p) | |
return np.sum(c <= 1.0) | |
b = perfplot.bench( | |
setup=lambda n: n, | |
kernels=[plain_loop, plain_loop2, numpy, numpy2], | |
n_range=[2**k for k in range(3, 23)], | |
equality_check=None | |
) | |
b.save("out.png") | |
b.show() |
Of course the slowest possible solution in Python is slower than a not-so-fleshed-out solution in Rust,
True but I cannot write naive Rust and use a sophisticated numerical library in Python for comparison either (plus it is easier to use just python without a venv in the demos) - this wasn't meant to be a real benchmark in the first place and the speed difference is orders of magnitude, no matter which python code is used - which is why I never bothered to optimise.
I mentioned in the comment (no idea why it was deleted) that there are problems which cannot be vectorized, for example solutions of first-order ODEs. My suggestion is to use those as examples next time you compare Python and Rust.
Good idea for a real world speed comparison, not sure it makes sense though to do that on youtube as Python and Rust both have fast development cycles rendering the video useless in a matter of weeks/months.
Why the youtube comment disappeared I don't know, I haven't touched anything, I just kept the email to respond to you later when I have time (I have moved to a new apartment) - maybe auto-delete because you had a link in your comment (antispam measure)?
Of course the slowest possible solution in Python is slower than a not-so-fleshed-out solution in Rust, simply because Rust is compiled and Python isn't. You wouldn't do that in Python though, you'd use NumPy. That's the default, not some obscure rewrite or so. Quite the contrary, using pure Python is unusual. That's why I find it inappropriate trying to compare pure Python with pure Rust.
I mentioned in the comment (no idea why it was deleted) that there are problems which cannot be vectorized, for example solutions of first-order ODEs. My suggestion is to use those as examples next time you compare Python and Rust.