In [1]:
import hope
hope.config.optimize = True
hope.config.verbose = True
hope.config.keeptemp = True
import numba
import numpy as np
import numexpr as ne
from util import perf_comp_data
from native_util import load
%load_ext cythonmagic
%load_ext version_information
%version_information numpy, Cython, numba, hope, numexpr
Out[1]:
In [2]:
def poly(res, arg):
res[:] = np.sin(arg)**2 + (arg**3 + arg**2 - arg - 1)/(arg**2 + 2*arg + 1) + np.cos(arg)**2
hope_poly = hope.jit(poly)
numba_poly = numba.jit(poly, nopython=False)
native_poly_mod = load("poly")
native_poly = native_poly_mod.run
In [3]:
%%cython
cimport cython
from libc.math cimport sin
from libc.math cimport cos
from libc.math cimport pow
@cython.boundscheck(False)
@cython.wraparound(False)
def cython_poly(double[:] res, double[:] arg):
for i in range(len(arg)):
i_arg = arg[i]
res[i] = pow(sin(i_arg),2) + (pow(i_arg,3) + pow(i_arg,2) - i_arg - 1)/(pow(i_arg,2) + 2*i_arg + 1) + pow(cos(i_arg),2)
In [4]:
%%cython
cimport cython
import numpy as np
cimport numpy as np
@cython.boundscheck(False)
@cython.wraparound(False)
def cython_numpy_poly(np.ndarray[np.double_t, ndim=1] res, np.ndarray[np.double_t, ndim=1] arg):
res[:] = np.sin(arg)**2 + (arg**3 + arg**2 - arg - 1)/(arg**2 + 2*arg + 1) + np.cos(arg)**2
In [5]:
# NumExpr version
import numexpr as ne
def numexpr_poly(res, arg):
res[:] = ne.evaluate("sin(arg)**2 + (arg**3 + arg**2 - arg - 1)/(arg**2 + 2*arg + 1) + cos(arg)**2")
In [7]:
arg = np.random.random(50000)
res = np.empty_like(arg)
res1 = np.empty_like(arg)
res2 = np.empty_like(arg)
res3 = np.empty_like(arg)
res4 = np.empty_like(arg)
res5 = np.empty_like(arg)
poly(res1, arg)
hope_poly(res2, arg)
numba_poly(res3, arg)
native_poly(res4, arg)
numexpr_poly(res5, arg)
assert np.allclose(res1, res2)
assert np.allclose(res1, res3)
assert np.allclose(res1, res4)
assert np.allclose(res1, res5)
In [8]:
print "python"
%timeit poly(res, arg)
print "hope"
%timeit hope_poly(res, arg)
print "numba"
%timeit numba_poly(res, arg)
print "cython"
%timeit cython_poly(res, arg)
print "cython numpy"
%timeit cython_numpy_poly(res, arg)
print "native"
%timeit native_poly(res, arg)
print "numexpr (1)"
ne.set_num_threads(1)
%timeit numexpr_poly(res, arg)
print "numexpr ({0})".format(ne.detect_number_of_cores())
ne.set_num_threads(ne.detect_number_of_cores())
%timeit numexpr_poly(res, arg)
In [9]:
ne.set_num_threads(8)
perf_comp_data(["poly",
"hope_poly",
"numba_poly",
"cython_poly",
"cython_numpy_poly",
"native_poly",
"numexpr_poly"],
7*["res, arg"], rep=100)
In [ ]: