Naively counting Pythagorean triples in Python and Julia
total = 0 | |
N = 300 | |
start_time = time() | |
for a in 0:(N - 1) | |
for b in 0:(N - 1) | |
for c in 0:(N - 1) | |
if a^2 + b^2 == c^2 | |
total = total + 1 | |
end | |
end | |
end | |
end | |
end_time = time() | |
end_time - start_time | |
# Repeat now that JIT has done its work | |
total = 0 | |
N = 300 | |
start_time = time() | |
for a in 0:(N - 1) | |
for b in 0:(N - 1) | |
for c in 0:(N - 1) | |
if a^2 + b^2 == c^2 | |
total = total + 1 | |
end | |
end | |
end | |
end | |
end_time = time() | |
println(end_time - start_time) |
function loop(N::Integer) | |
total = 0 | |
start_time = time() | |
for a in 0:(N - 1) | |
for b in 0:(N - 1) | |
for c in 0:(N - 1) | |
if a^2 + b^2 == c^2 | |
total = total + 1 | |
end | |
end | |
end | |
end | |
end_time = time() | |
return end_time - start_time | |
end | |
loop(300) | |
# Repeat now that JIT has done its work | |
println(loop(300)) |
This comment has been minimized.
This comment has been minimized.
The array version is intentionally very compressed, but still, I'd rather be able to use arrays to solve this sort of problem instead of three nested loops. Does Julia perform as well on that front?
|
This comment has been minimized.
This comment has been minimized.
Under PyPy I got a mean of 45ms over 100 runs, also on a recent Macbook Pro. 4.5x faster than the PyPy JIT is pretty awesome. |
This comment has been minimized.
This comment has been minimized.
Using cython via ipython notebook: paste this into the next cell block:
paste this into the next cell block: 3 loops, best of 3: 19.1 ms per loop |
This comment has been minimized.
This comment has been minimized.
If |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
On my MacBook Pro, the timings are: