Created
May 13, 2021 07:53
-
-
Save nschloe/4e1007dbcff37c5d03a77cf480c89bf4 to your computer and use it in GitHub Desktop.
Monte Carlo test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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)?