50
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numbaによるfor文の高速化とjitの引数

Last updated at Posted at 2019-03-04

pythonのfor文は遅い.Numbaが使いやすそう.

そこまではわかった.Numbaの使い方も調べた.うん,@jitを頭に置けば良いのだろう.だがしかし,引数や返り値を指定する方法があるときいたが,どのようにすればよいかわからない.そのようなときに参考にすべきページ.ちなみに型指定をすると10倍程度高速化するそう.

参考はこちら


追記

jitをクラスに適応する方法はこちら


import numpy as np
from numba import jit, f8, i8, b1, void

@jit(返り値の型(引数1の型,引数2の型,...,引数nの型))
def function(引数1,引数2,...,引数n):
  処理
 

とりあえず,こんな形でおいてあげれば大丈夫.

宣言方法
int i8
float f8
string u1
boolean b1
返り値なし void
float 1次配列 f8[:]
float 2次配列 f8[:,:]

例1

@jit(void(i8[:]))
def print_array(xs):
  for x in xs:
    print("* " * x)

xs = np.array([i for i in range(100)])
print_array(xs)

例2

import random
import math

@jit(b1[:](i8[:]))
def is_there_one(xs):
  for x in xs:
    if x == 1:
      return True
  
  return False

xs = np.array([math.ceil(random.random * 100) for i in range(100)])
print("Is there any one in the array? -- {}.".format(is_there_one(xs)))
50
56
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?