Permalink
Browse files

genprime.pyx: Cython implementation added

Signed-off-by: Steven Noonan <steven@uplinklabs.net>
  • Loading branch information...
1 parent cd02d81 commit dd2718702166da89ae770bc1ee066c889efa87c8 @tycho committed Jan 3, 2012
Showing with 64 additions and 1 deletion.
  1. +10 −1 Makefile
  2. +54 −0 genprime.pyx
View
11 Makefile
@@ -1,6 +1,6 @@
ARGS=25000 100000
-all: genprime-java genprime-c genprime-f90 genprime-py27 genprime-py30 genprime-objc genprime-cpp genprime-cs genprime-c-llvm genprime-c-icc genprime-c-clang
+all: genprime-java genprime-c genprime-f90 genprime-pyx genprime-py27 genprime-py30 genprime-objc genprime-cpp genprime-cs genprime-c-llvm genprime-c-icc genprime-c-clang
clean:
rm -f genprime.*.py *.pyc *.class genprime-* *.s *.bc *.ll *.rbc
@@ -35,6 +35,8 @@ version:
@echo
-php --version
@echo
+ -cython --version
+ @echo
-python2.7 --version
@echo
-python3.0 --version
@@ -93,6 +95,9 @@ run: all
@echo "genprime (Python 2.7)"
@-python2.7 genprime.27.pyc $(ARGS)
@echo
+ @echo "genprime (Python 2.7 + Cython)"
+ @-./genprime-pyx $(ARGS)
+ @echo
@echo "genprime (Python 2.7 + Psyco)"
@-python2.7 genprime.27.pyc -p $(ARGS)
@echo
@@ -156,6 +161,10 @@ genprime-cs.exe: genprime.cs
-gmcs -out:genprime-cs.exe -optimize+ genprime.cs
@echo
+genprime-pyx: genprime.pyx
+ -cython --embed -o genprime-pyx.c genprime.pyx
+ -gcc -O3 -pipe $(shell pkg-config --cflags python) genprime-pyx.c -o genprime-pyx $(shell pkg-config --libs python)
+
genprime-py27: genprime.27.pyc
genprime-py30: genprime.30.pyc
View
54 genprime.pyx
@@ -0,0 +1,54 @@
+import time
+import sys
+from math import sqrt
+
+cdef isprime(unsigned int x):
+ cdef unsigned int y, lim
+ if x < 2:
+ return False
+ if x == 2:
+ return True
+ if x % 2 == 0:
+ return False
+ if x < 9:
+ return True
+ if (x + 1) % 6 != 0:
+ if (x - 1) % 6 != 0:
+ return False
+ lim = int(sqrt(x) + 1)
+ for y from 3 <= y < lim by 2:
+ if x % y == 0:
+ return False
+ return True
+
+cdef genprime(unsigned int max):
+ cdef unsigned int count, current
+ count = 0
+ current = 1
+ while count < max:
+ if isprime(current):
+ count = count + 1
+ current = current + 1
+ return current - 1
+
+def main():
+ ind=1
+ if sys.argv[1] == '-p':
+ ind = ind + 1
+ import psyco
+ psyco.full()
+ try:
+ start=int(sys.argv[ind])
+ stop=int(sys.argv[ind + 1])+1
+ except IndexError:
+ quit()
+ for x in range(start, stop, start):
+ begin = time.clock()
+ last = genprime(x)
+ end = time.clock()
+ duration = end - begin
+ print('Found %(count)8d primes in %(time)10.5f seconds (last was %(last)10d)' % {'count': x, 'time': duration, 'last': last})
+
+if __name__ == "__main__":
+ main()
+

0 comments on commit dd27187

Please sign in to comment.