python - 如何从 numba 结构类型创建结构?

标签 python numba

我可以定义一个 numba 结构类型:

from numba import struct, int32

my_struct_type = struct([('value_a', int32), ('value_b', int32)])

既然我有了类型,我该如何创建一个实际的结构?

最佳答案

numba.struct 不再存在,您现在可以简单地传入标准 numpy 数组和您自定义的复杂 dtype....

import numpy as np # version 1.10.1
import numba # version 0.22.1

@numba.jit(nopython=True)
def sum_basic_array(a):
    ret = 0
    for aa in a:
        ret += aa
    return ret

@numba.jit(nopython=True)
def sum_struct_array(a):
    ret = 0
    for aa in a:
        ret += aa.sub_0
    return ret

x_basic = np.arange(20000*3, dtype=np.uint32)
x_struct = x_basic.view(dtype=np.dtype([('sub_0', np.int32),
                                        ('sub_1', np.float64)]))

%timeit sum_basic_array(x_basic) # 18 µs
%timeit sum_struct_array(x_struct) # 8 µs
%timeit sum_struct_array(x_struct.view(np.recarray)) # 40 µs

请注意,sum_struct_array 执行的迭代次数是原来的三分之一,因此它更快也就不足为奇了。

关于python - 如何从 numba 结构类型创建结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19605757/

相关文章:

python - pandas:T/F 表示两个范围是否相交

Python方法对url的 "non-standard"部分进行引用

python - 模块 'numba.findlib' 没有属性 'get_lib_dir'

python - 有什么办法可以在 numba 中将 timedelta64 转换为 int64 吗?

python - Cuda 并行化内核共享计数器变量

python - 操作系统错误: [WinError 10038] An operation was attempted on something that is not a socket - Python sockets?

python - 将 pickle.dumps 输出写入文件

python - python 函数的显式签名,参数包括 2d numpy 数组

python - 在 pandas 的 rolling().apply() 中,args 在 enigne ="numba"时被缓存

python - 尝试从 pandas 数据帧创建嵌套字典