Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Last active August 10, 2018 10:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save johnmyleswhite/5556201 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/5556201 to your computer and use it in GitHub Desktop.
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))
total = 0
N = 300
from time import time
start = time()
for a in range(N):
for b in range(N):
for c in range(N):
if a**2 + b**2 == c**2:
total = total + 1
end = time()
print(end - start)
@vgoklani
Copy link

Using cython via ipython notebook:
%load_ext cythonmagic

paste this into the next cell block:

%%cython
import numpy as np

cimport numpy as np
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
cpdef calc(N=300):
    cdef:
        np.int total = 0
        Py_ssize_t i, j, k
    for i in xrange(N):
        for j in xrange(N):
            for k in xrange(N):
                if i**2 + j**2 == k**2:
                    total = total + 1
    return total

paste this into the next cell block:
%timeit -n3 calc()

3 loops, best of 3: 19.1 ms per loop

@diegozea
Copy link

diegozea commented Jun 7, 2013

If N is defined as const in JuliaGlobals, the time changes from 660 ms to 34 ms on my machine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment