Pythonのnumpyライブラリは思っていたより高速だった

投稿者: | 2020年8月24日

画像を処理しようとR-G-Bの各々の値をいじくろうとして、古典的にimage[i][j]を書き換えていたらメッチャ遅かった。こういう時こそ行列でまるごと計算できるnumpyの登場だよな、と思って処理したらメッチャ速かった。どの程度速くなるかは使っているハードウェア依存だと思うけれど、とりあえず、どれくらい速いか試してみる価値はある。ちなみに下のテストコードをpython3.7.3 + Intel Core i7-6500U CPU @ 2.50GHzの組み合わせで動かすと800から1000倍程度速かった。

#!/bin/env python
import numpy as np
import time
hw=(720,1280)
ma = np.full_like(np.zeros(hw, np.int16), 64, dtype=np.int16)
mb = np.full_like(np.zeros(hw, np.int16), 128, dtype=np.int16)
t0 = time.time()
mc = ma + mb
t1 = time.time()
t2 = t1 - t0
print("ma + mb: "+ str(int(t2*100000)/100) + "ms")
t0 = time.time()
for i in range(hw[0]):
    for j in range(hw[1]):
        mc[i][j] = ma[i][j] + mb[i][j]
t1 = time.time()
t3 = t1 - t0
print("ma[i][j] + mb[i][j]: "+ str(int(t3*100000)/100) + "ms")
print("np is " + str(int(t3/t2)) + " times faster than loop calc.")