【问题标题】:Loops over list 20x faster than over ndarray列表循环比 ndarray 快 20 倍
【发布时间】:2014-06-09 20:54:44
【问题描述】:

我不明白为什么在以下循环中 f?cf? 慢 20 倍。

我了解类型定义允许 Cython 利用 C 速度。

我在这里错过了什么?

谢谢

%%cython
import numpy as np
cimport numpy as np


cpdef f1(l):
    for k in l:
        k

cpdef f1c(np.ndarray npl):
    cdef int i = 0
    for i in range(npl.shape[0]):
        npl[i]

cpdef f2(n):
    for k in n:
        k

cpdef f2c(np.ndarray npn):
    cdef int i = 0
    for i in range(npn.shape[0]):
        npn[i]

还有时间:

l = ["lol"]*100000
npl = np.array(l, dtype=np.str)

n = [1]*100000
npn = np.array(n, dtype=np.int)



%timeit f1(l)

%timeit f1c(npl)

%timeit f2(n)

%timeit f2c(npn)

1000 loops, best of 3: 484 µs per loop
100 loops, best of 3: 13.1 ms per loop
1000 loops, best of 3: 483 µs per loop
100 loops, best of 3: 12.4 ms per loop

【问题讨论】:

标签: python performance list numpy cython


【解决方案1】:

当您指定数组的数据类型和维数时,numpy 上的循环至少快一个数量级:

def f2c(np.ndarray[np.int_t, ndim=1] npn):
    cdef int i = 0
    for i in range(npn.shape[0]):
        npn[i]

同样,对于字符串大小写,我得到了两倍快的循环:

def f1c(np.ndarray[object, ndim=1] npl):
    cdef int i = 0
    for i in range(npl.shape[0]):
        npl[i]

在这种情况下你必须使用:

npl = np.array(l, dtype=object)

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 2017-11-29
    • 2014-03-12
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多