Skip to content

Instantly share code, notes, and snippets.

@erikkaplun
Created March 8, 2012 13:31
Show Gist options
  • Save erikkaplun/2000994 to your computer and use it in GitHub Desktop.
Save erikkaplun/2000994 to your computer and use it in GitHub Desktop.
Cython factorial bench
public class Fact {
static private int factorial(int n) {
int ret = 1;
for (int j = n; j > 0; j -= 1) {
ret *= j;
}
return ret;
}
static private void bench() {
for (int i = 0; i < 1000; i += 1) {
factorial(5000);
}
}
static public void main(String[] args) {
long start = System.currentTimeMillis();
bench();
long stop = System.currentTimeMillis();
System.out.print("Time consumed: ");
System.out.print(stop - start);
System.out.println("ms");
}
}
def fact_cy(int n):
cdef int i, ret
ret = 1
for i in range(n):
ret *= n
return ret
def bench_cy():
for i in range(1000):
fact_cy(5000)
def fact_py(n):
ret = 1
for _ in range(n):
ret *= n
return ret
def bench_py():
for _ in range(1000):
fact_py(5000)
import pyximport
pyximport.install()
import time
import factorial
cy_start = time.time()
factorial.bench_cy()
cy_end = time.time()
print "Cython: %sms" % ((cy_end - cy_start) * 1000)
py_start = time.time()
factorial.bench_py()
py_end = time.time()
print "Python: %sms" % ((py_end - py_start) * 1000)
print "Speed-up: %s" % ((py_end - py_start) / (cy_end - cy_start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment