UND_advanced_examples

141 days ago by gsever

from timeit import default_timer as clock def f(x): return x**3 + x**2 + x t1 = clock() map(f, range(1000000)) t2 = clock() #print "Elapsed time using single process:", t2-t1 
       
from timeit import default_timer as clock from multiprocessing import Pool def f(x): return x**3 + x**2 + x if __name__ == '__main__': t1 = clock() pool = Pool(processes=2) # start 2 worker processes dummy = pool.map(f, range(1000000)) t2 = clock() #print "Elapsed time using two processes:", t2-t1 
       
 
       
class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): if not args in self.memo: self.memo[args] = self.f(*args) return self.memo[args] @Memoize def factorial(k): if k < 2: return 1 return k * factorial(k - 1) def factorial2(k): if k < 2: return 1 return k * factorial2(k - 1) 
       
timeit('factorial2(100)') 
       
timeit('factorial(100)') 
       
 
       
def f1(x): return 1/(x**3 + 2*x**2) def integrate_f1(a, b, N): s = 0 dx = (b-a) / N for i in range(N): s += f1(a+i*dx) return s * dx 
       
timeit('integrate_f1(4, 10, 1000)') 
       
%cython cdef double f2(double x): return 1/(x**3 + 2*x**2) cpdef double integrate_f2(int a, int b, int N): cdef double s cdef int i s = 0 dx = (b-a) / N for i in range(N): s += f2(a+i*dx) return s * dx 
timeit('integrate_f2(4, 10, 1000)')