Commit 6dd63258 authored by Stefan Behnel's avatar Stefan Behnel

modernise demos and make them Py2/3 compatible

parent 9b925e03
from __future__ import absolute_import, print_function
import sys import sys
f1 = open(sys.argv[1]) f1 = open(sys.argv[1])
f2 = open(sys.argv[2]) f2 = open(sys.argv[2])
try: try:
if f1.read() != f2.read(): if f1.read() != f2.read():
print ("Files differ") print("Files differ")
sys.exit(1) sys.exit(1)
else: else:
print ("Files identical") print("Files identical")
finally: finally:
f1.close() f1.close()
f2.close() f2.close()
# cython: language_level=3
print __name__ print(__name__)
if __name__ == "__main__": if __name__ == "__main__":
print "Hi, I'm embedded." print("Hi, I'm embedded.")
else: else:
print "I'm being imported." print("I'm being imported.")
# cython: language_level=3
import lcmath import lcmath
def nCr(n, r): def nCr(n, r):
"""Return the number of ways to choose r elements of a set of n.""" """Return the number of ways to choose r elements of a set of n."""
return lcmath.exp( lcmath.lfactorial(n) - lcmath.lfactorial(r) return lcmath.exp(
- lcmath.lfactorial(n-r) ) lcmath.lfactorial(n) -
lcmath.lfactorial(r) -
lcmath.lfactorial(n-r)
)
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys
...@@ -11,4 +17,4 @@ if __name__ == "__main__": ...@@ -11,4 +17,4 @@ if __name__ == "__main__":
sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0]) sys.stderr.write("USAGE: %s n r\nPrints n-choose-r.\n" % sys.argv[0])
sys.exit(2) sys.exit(2)
n, r = map(float, sys.argv[1:]) n, r = map(float, sys.argv[1:])
print nCr(n, r) print(nCr(n, r))
# cython: language_level=3
cdef extern from "math.h": cdef extern from "math.h":
double c_lgamma "lgamma" (double) double c_lgamma "lgamma" (double)
double c_exp "exp" (double) double c_exp "exp" (double)
def exp(n): def exp(n):
"""Return e**n.""" """Return e**n."""
return c_exp(n) return c_exp(n)
def lfactorial(n): def lfactorial(n):
"""Return an estimate of the log factorial of n.""" """Return an estimate of the log factorial of n."""
return c_lgamma(n+1) return c_lgamma(n+1)
def factorial(n): def factorial(n):
"""Return an estimate of the factorial of n.""" """Return an estimate of the factorial of n."""
return c_exp( c_lgamma(n+1) ) return c_exp( c_lgamma(n+1) )
...@@ -21,4 +26,4 @@ if __name__ == "__main__": ...@@ -21,4 +26,4 @@ if __name__ == "__main__":
sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0]) sys.stderr.write("USAGE: %s n\nPrints n!.\n" % sys.argv[0])
sys.exit(2) sys.exit(2)
n, = map(float, sys.argv[1:]) n, = map(float, sys.argv[1:])
print factorial(n) print(factorial(n))
# cython: language_level=3
def f(x): def f(x):
return x**2-x return x**2-x
def integrate_f(a, b, N): def integrate_f(a, b, N):
s = 0.0 s = 0.0
dx = (b-a)/N dx = (b-a)/N
......
# cython: language_level=3
cdef double f(double x) except? -2: cdef double f(double x) except? -2:
return x**2-x return x**2-x
def integrate_f(double a, double b, int N): def integrate_f(double a, double b, int N):
cdef int i cdef int i
s = 0.0 s = 0.0
......
from __future__ import absolute_import, print_function
import timeit import timeit
import integrate0, integrate1, integrate2 import integrate0, integrate1, integrate2
...@@ -5,9 +7,9 @@ import integrate0, integrate1, integrate2 ...@@ -5,9 +7,9 @@ import integrate0, integrate1, integrate2
number = 10 number = 10
py_time = None py_time = None
for m in ('integrate0', 'integrate1', 'integrate2'): for m in ('integrate0', 'integrate1', 'integrate2'):
print m print(m)
t = min(timeit.repeat("integrate_f(0.0, 10.0, 10000000)", "from %s import integrate_f" % m, number=number)) t = min(timeit.repeat("integrate_f(0.0, 10.0, 10000000)", "from %s import integrate_f" % m, number=number))
if py_time is None: if py_time is None:
py_time = t py_time = t
print " ", t / number, "s" print(" ", t / number, "s")
print " ", py_time / t print(" ", py_time / t)
from __future__ import absolute_import, print_function
import os import os
import sys import sys
...@@ -8,7 +10,7 @@ from Cython.Build import cythonize ...@@ -8,7 +10,7 @@ from Cython.Build import cythonize
# For demo purposes, we build our own tiny library. # For demo purposes, we build our own tiny library.
try: try:
print "building libmymath.a" print("building libmymath.a")
assert os.system("gcc -shared -fPIC -c mymath.c -o mymath.o") == 0 assert os.system("gcc -shared -fPIC -c mymath.c -o mymath.o") == 0
assert os.system("ar rcs libmymath.a mymath.o") == 0 assert os.system("ar rcs libmymath.a mymath.o") == 0
except: except:
......
cimport numpy cimport numpy as cnp
import numpy
def sum_of_squares(numpy.ndarray[double, ndim=1] arr):
def sum_of_squares(cnp.ndarray[double, ndim=1] arr):
cdef long N = arr.shape[0] cdef long N = arr.shape[0]
cdef double ss = 0 cdef double ss = 0
for i in range(N): for i in range(N):
......
# cython: language_level=3
# distutils: extra_compile_args = -O3 # distutils: extra_compile_args = -O3
import cython cimport cython
ctypedef fused INT: ctypedef fused INT:
int int
...@@ -15,6 +16,7 @@ ctypedef fused C_INT: ...@@ -15,6 +16,7 @@ ctypedef fused C_INT:
unsigned int unsigned int
unsigned long long unsigned long long
@cython.overflowcheck(False) @cython.overflowcheck(False)
def fib(INT n): def fib(INT n):
""" """
...@@ -54,12 +56,13 @@ def collatz(INT n): ...@@ -54,12 +56,13 @@ def collatz(INT n):
cdef INT k = 0 cdef INT k = 0
while n != 1: while n != 1:
if n % 2 == 0: if n % 2 == 0:
n /= 2 n //= 2
else: else:
n = 3*n + 1 n = 3*n + 1
k += 1 k += 1
return int(k) return int(k)
@cython.overflowcheck(True) @cython.overflowcheck(True)
@cython.overflowcheck.fold(False) @cython.overflowcheck.fold(False)
def collatz_overflow(INT n): def collatz_overflow(INT n):
...@@ -74,12 +77,13 @@ def collatz_overflow(INT n): ...@@ -74,12 +77,13 @@ def collatz_overflow(INT n):
cdef INT k = 0 cdef INT k = 0
while n != 1: while n != 1:
if n % 2 == 0: if n % 2 == 0:
n /= 2 n //= 2
else: else:
n = 3*n + 1 n = 3*n + 1
k += 1 k += 1
return int(k) return int(k)
@cython.overflowcheck(True) @cython.overflowcheck(True)
@cython.overflowcheck.fold(True) @cython.overflowcheck.fold(True)
def collatz_overflow_fold(INT n): def collatz_overflow_fold(INT n):
...@@ -94,14 +98,13 @@ def collatz_overflow_fold(INT n): ...@@ -94,14 +98,13 @@ def collatz_overflow_fold(INT n):
cdef INT k = 0 cdef INT k = 0
while n != 1: while n != 1:
if n % 2 == 0: if n % 2 == 0:
n /= 2 n //= 2
else: else:
n = 3*n + 1 n = 3*n + 1
k += 1 k += 1
return int(k) return int(k)
@cython.overflowcheck(False) @cython.overflowcheck(False)
def factorial(INT n): def factorial(INT n):
""" """
...@@ -129,7 +132,6 @@ def factorial_overflow(INT n): ...@@ -129,7 +132,6 @@ def factorial_overflow(INT n):
return int(res) return int(res)
@cython.overflowcheck(False) @cython.overflowcheck(False)
def most_orthogonal(C_INT[:,::1] vectors): def most_orthogonal(C_INT[:,::1] vectors):
cdef C_INT n = vectors.shape[0] cdef C_INT n = vectors.shape[0]
...@@ -148,6 +150,7 @@ def most_orthogonal(C_INT[:,::1] vectors): ...@@ -148,6 +150,7 @@ def most_orthogonal(C_INT[:,::1] vectors):
min_pair = i, j min_pair = i, j
return vectors[i], vectors[j] return vectors[i], vectors[j]
@cython.overflowcheck(True) @cython.overflowcheck(True)
@cython.overflowcheck.fold(False) @cython.overflowcheck.fold(False)
def most_orthogonal_overflow(C_INT[:,::1] vectors): def most_orthogonal_overflow(C_INT[:,::1] vectors):
...@@ -167,6 +170,7 @@ def most_orthogonal_overflow(C_INT[:,::1] vectors): ...@@ -167,6 +170,7 @@ def most_orthogonal_overflow(C_INT[:,::1] vectors):
min_pair = i, j min_pair = i, j
return vectors[i], vectors[j] return vectors[i], vectors[j]
@cython.overflowcheck(True) @cython.overflowcheck(True)
@cython.overflowcheck.fold(True) @cython.overflowcheck.fold(True)
def most_orthogonal_overflow_fold(C_INT[:,::1] vectors): def most_orthogonal_overflow_fold(C_INT[:,::1] vectors):
......
from __future__ import absolute_import, print_function
from overflow_perf import * from overflow_perf import *
import sys import sys
...@@ -11,7 +13,7 @@ except ImportError: ...@@ -11,7 +13,7 @@ except ImportError:
def run_tests(N): def run_tests(N):
global f global f
for func in most_orthogonal, fib, collatz, factorial: for func in most_orthogonal, fib, collatz, factorial:
print func.__name__ print(func.__name__)
for type in ['int', 'unsigned int', 'long long', 'unsigned long long', 'object']: for type in ['int', 'unsigned int', 'long long', 'unsigned long long', 'object']:
if func == most_orthogonal: if func == most_orthogonal:
if type == 'object' or np == None: if type == 'object' or np == None:
...@@ -23,15 +25,16 @@ def run_tests(N): ...@@ -23,15 +25,16 @@ def run_tests(N):
else: else:
arg = N arg = N
try: try:
print "%s[%s](%s)" % (func.__name__, type, N) print("%s[%s](%s)" % (func.__name__, type, N))
with_overflow = my_timeit(globals()[func.__name__ + "_overflow"][type], arg) with_overflow = my_timeit(globals()[func.__name__ + "_overflow"][type], arg)
no_overflow = my_timeit(func[type], arg) no_overflow = my_timeit(func[type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow) print("\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow))
if func.__name__ + "_overflow_fold" in globals(): if func.__name__ + "_overflow_fold" in globals():
with_overflow = my_timeit(globals()[func.__name__ + "_overflow_fold"][type], arg) with_overflow = my_timeit(globals()[func.__name__ + "_overflow_fold"][type], arg)
print "\t%0.04e\t%0.04e\t%0.04f" % (no_overflow, with_overflow, with_overflow / no_overflow), "(folded)" print("\t%0.04e\t%0.04e\t%0.04f (folded)" % (
no_overflow, with_overflow, with_overflow / no_overflow))
except OverflowError: except OverflowError:
print " ", "Overflow" print(" ", "Overflow")
def my_timeit(func, N): def my_timeit(func, N):
global f, arg global f, arg
...@@ -44,10 +47,11 @@ def my_timeit(func, N): ...@@ -44,10 +47,11 @@ def my_timeit(func, N):
break break
return res / times return res / times
params = sys.argv[1:] params = sys.argv[1:]
if not params: if not params:
params = [129, 9, 97] params = [129, 9, 97]
for arg in params: for arg in params:
print print()
print "N", arg print("N", arg)
run_tests(int(arg)) run_tests(int(arg))
print "starting" # cython: language_level=3
print("starting")
def primes(int kmax): def primes(int kmax):
# cdef int n, k, i # cdef int n, k, i
...@@ -10,11 +12,11 @@ def primes(int kmax): ...@@ -10,11 +12,11 @@ def primes(int kmax):
n = 2 n = 2
while k < kmax: while k < kmax:
i = 0 i = 0
while i < k and n % p[i] <> 0: while i < k and n % p[i] != 0:
i = i + 1 i += 1
if i == k: if i == k:
p[k] = n p[k] = n
k = k + 1 k += 1
result.append(n) result.append(n)
n = n + 1 n += 1
return result return result
from __future__ import absolute_import, print_function
import sys import sys
from primes import primes from primes import primes
if len(sys.argv) >= 2: if len(sys.argv) >= 2:
n = int(sys.argv[1]) n = int(sys.argv[1])
else: else:
n = 1000 n = 1000
print primes(n)
print(primes(n))
from __future__ import absolute_import, print_function
from spam import Spam from spam import Spam
s = Spam() s = Spam()
print "Created:", s print("Created:", s)
s.set_amount(42) s.set_amount(42)
print "Amount =", s.get_amount() print("Amount =", s.get_amount())
s.describe() s.describe()
s = None s = None
# cython: language_level=3
# #
# Example of an extension type. # Example of an extension type.
# #
...@@ -9,7 +11,7 @@ cdef class Spam: ...@@ -9,7 +11,7 @@ cdef class Spam:
self.amount = 0 self.amount = 0
def __dealloc__(self): def __dealloc__(self):
print self.amount, "tons of spam is history." print(self.amount, "tons of spam is history.")
def get_amount(self): def get_amount(self):
return self.amount return self.amount
...@@ -18,4 +20,4 @@ cdef class Spam: ...@@ -18,4 +20,4 @@ cdef class Spam:
self.amount = new_amount self.amount = new_amount
def describe(self): def describe(self):
print self.amount, "tons of spam!" print(self.amount, "tons of spam!")
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment