numba

# without Numba

def sum1d_wonumba(arr):

result = 0.0

for i in range(len(arr)):

result += arr[i]

return result

# with Numba

@jit

def sum1d_wnumba(arr):

result = 0.0

for i in range(len(arr)):

result += arr[i]

return result

import numpy as np

# jit decorator tells Numba to compile this function.

# The argument types will be inferred by Numba when function is called.

なお,関数は以下のとおりである.

その結果を添付のw_wo_numba.pngに示す.numbaを使うことで,ざっと100倍程度高速になる.また,numbaを使わない場合はfloat64の方がfloat32よりも高速だが,numbaを使うと逆にfloat32の方がfloat64よりも高速になる.float32はnumbaを使うことで200倍程度高速になる.

したがって,numbaを使い配列をfloat64ではなくfloat32にすることが,高速な関数を作るうえで有効である.

まずnumbaでどれくらい高速になるかを調べるために,numpy data arrayの要素について総和を求める関数を,numbaを用いる場合と用いない場合で作成した.これを,numpy data array おwfloat32とfloat64で作成して実行し,異なる配列サイズに対して実行時間がどう依存するかを調べた.この実行速度には,配列を初期化する時間は含めていない.

numbaはfor loopを使うなどして遅いpythonの関数をコンパイルして高速にするパッケージである.使い方は極めて簡単で,for loopを使って遅い関数の直前に,@jitという一行を置くだけでいい.型指定をする方法もあるが,それによって有意に速くなるということは確認できなかった.これは,ループを使って和を計算するという単純な例であることがよく無かったのかもしれない.

Numba is a package that speeds up slow python functions, such as by using for loop, by compiling. It's very easy to use, just put @jit just before a slow function.

To find out how fast numba is, we created a function that sums up the elements of a numpy data array with and without numba for float32 and float64, and we examined how the execution time depends on the different array sizes. This execution speed does not include the time to initialize the array.

The result is shown in the attached w_wo_numba.png. By using numba, the speed is roughly 100 times faster. When numba is not used, float64 is faster than float32. However, when numba is used, float32 is faster than float64. float32 is about 200 times faster by using numba.

Therefore, using numba with numpy data array of float32 rather than float64 is effective for creating high-speed functions.

The function used is shown below.

import numpy as np

# jit decorator tells Numba to compile this function.

# The argument types will be inferred by Numba when function is called.

# with Numba

@jit

def sum1d_wnumba(arr):

result = 0.0

for i in range(len(arr)):

result += arr[i]

return result

# without Numba

def sum1d_wonumba(arr):

result = 0.0

for i in range(len(arr)):

result += arr[i]

return result