Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one create a struct from a numba struct type?

Tags:

python

numba

I can define a numba struct type with:

from numba import struct, int32

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

Now that I have the type, how do I create an actual struct?

like image 765
Yuval Langer Avatar asked Oct 26 '13 10:10

Yuval Langer


1 Answers

numba.struct no longer exists, you can now simply pass in standard numpy arrays with your custom complicated 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

Note that the sum_struct_array is doing one third as many iterations, so it shouldn't be a surprise that it's faster.

like image 134
dan-man Avatar answered Oct 14 '22 05:10

dan-man