python 调用 c numpy 数组_python-与C数组相比,使用NumPy数组memoryview的C...

我从benchmark遇到了一个很奇怪的结果

这些都是Bubbleort实现的不同风味,n = 10 ^ 4时最快的方法是在内部将Python列表转换为C数组.相比之下,黄线对应于我正在将NumPy数组与memoryview一起使用的代码.我希望结果反之亦然.我(和同事)重复了几次基准测试,始终得到相同的结果.也许有人对这里发生的事情有所了解…

图中的黑线将与代码对应:

%%cython

cimport cython

from libc.stdlib cimport malloc, free

def cython_bubblesort_clist(a_list):

"""

The Cython implementation of bubble sort with internal

conversion between Python list objects and C arrays.

"""

cdef int *c_list

c_list = malloc(len(a_list)*cython.sizeof(int))

cdef int count, i, j # static type declarations

count = len(a_list)

# convert Python list to C array

for i in range(count):

c_list[i] = a_list[i]

for i in range(count):

for j in range(1, count):

if c_list[j] < c_list[j-1]:

c_list[j-1], c_list[j] = c_list[j], c_list[j-1]

# convert C array back to Python list

for i in range(count):

a_list[i] = c_list[i]

free(c_list)

return a_list

以及此代码的粉色行:

%%cython

import numpy as np

cimport numpy as np

cimport cython

def cython_bubblesort_numpy(long[:] np_ary):

"""

The Cython implementation of bubble sort with NumPy memoryview.

"""

cdef int count, i, j # static type declarations

count = np_ary.shape[0]

for i in range(count):

for j in range(1, count):

if np_ary[j] < np_ary[j-1]:

np_ary[j-1], np_ary[j] = np_ary[j], np_ary[j-1]

return np.asarray(np_ary)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值