LoginSignup
1
2

More than 5 years have passed since last update.

Numpyは割り算をシフト演算に置き換えると速い

Posted at
img = np.arange(1000, dtype=np.uint16)

%timeit a = (img >> 3)
2.06 µs ± 9.03 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit a = (img / 8)
3.01 µs ± 27.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit a = (img / 8).astype(np.uint16)
4.55 µs ± 12.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

おそらく型の問題。Pythonはint / intの返す型がfloatなので、Numpyもそれに倣ってnp.int32 / np.int32の返す型がnp.float64になる。

割り算をシフト演算に置き換える、というと遠い昔にコンパイラの仕事になったような話だが、2019年にもなってからゾンビのように復活した。

1
2
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
1
2