【发布时间】:2014-05-28 04:11:39
【问题描述】:
我一直在尝试用 python 编写 cffi 模块,它们的速度让我怀疑我是否正确使用了标准 python。这让我想完全切换到C!说实话,有一些很棒的 python 库我永远无法用 C 重新实现自己,所以这比任何事情都更具假设性。
这个例子展示了 python 中的 sum 函数与一个 numpy 数组一起使用,以及它与 c 函数相比有多慢。有没有更快的 Python 方法来计算 numpy 数组的总和?
def cast_matrix(matrix, ffi):
ap = ffi.new("double* [%d]" % (matrix.shape[0]))
ptr = ffi.cast("double *", matrix.ctypes.data)
for i in range(matrix.shape[0]):
ap[i] = ptr + i*matrix.shape[1]
return ap
ffi = FFI()
ffi.cdef("""
double sum(double**, int, int);
""")
C = ffi.verify("""
double sum(double** matrix,int x, int y){
int i, j;
double sum = 0.0;
for (i=0; i<x; i++){
for (j=0; j<y; j++){
sum = sum + matrix[i][j];
}
}
return(sum);
}
""")
m = np.ones(shape=(10,10))
print 'numpy says', m.sum()
m_p = cast_matrix(m, ffi)
sm = C.sum(m_p, m.shape[0], m.shape[1])
print 'cffi says', sm
只是为了展示功能的工作原理:
numpy says 100.0
cffi says 100.0
现在,如果我对这个简单的函数计时,我发现 numpy 真的很慢! 我以正确的方式使用 numpy 吗?有没有更快的方法在python中计算总和?
import time
n = 1000000
t0 = time.time()
for i in range(n): C.sum(m_p, m.shape[0], m.shape[1])
t1 = time.time()
print 'cffi', t1-t0
t0 = time.time()
for i in range(n): m.sum()
t1 = time.time()
print 'numpy', t1-t0
次:
cffi 0.818415880203
numpy 5.61657714844
【问题讨论】:
-
使用timeit 模块进行基准测试。如果你安装了 ipython,试试
%timeit np.sum(np.sum(m))和` %timeit np.matrix.sum(x)` garbage collection etc might be an issue othervice -
可能大部分来自 python 开销,尝试使用更大的数组说
1E3x1E3并减少循环次数会看到更多可比时间。
标签: python c numpy pypy python-cffi