我测试过的所有建议的方法,加上
np.array(map(f, x))与
perfplot(我的一个小项目)。
消息1:如果可以使用numpy的本机函数,请执行此操作。
如果你想已经矢量化功能的矢量(如
x**2在原岗位的例子),使用的是多比什么都更快(注意对数标度):
如果你确实需要向量化,那么使用哪种变体并不重要。
复制剧情的代码:
import numpy as npimport perfplotimport mathdef f(x): # return math.sqrt(x) return np.sqrt(x)vf = np.vectorize(f)def array_for(x): return np.array([f(xi) for xi in x])def array_map(x): return np.array(list(map(f, x)))def fromiter(x): return np.fromiter((f(xi) for xi in x), x.dtype)def vectorize(x): return np.vectorize(f)(x)def vectorize_without_init(x): return vf(x)perfplot.show( setup=lambda n: np.random.rand(n), n_range=[2**k for k in range(20)], kernels=[ f, array_for, array_map, fromiter, vectorize, vectorize_without_init ], xlabel='len(x)', )



