Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@meshidenn

概要

これをできるだけ速く行いたいので、速度比較して見た。

• 2019/07更新: 配列の要素数が少なすぎて、呼び出しのオーバヘットが大きくなっているのではないかと言うご指摘を踏まえて更新しました。

問題設定・評価

jupyterの `%%timeit` で評価をおこなった

配列が長い時

``````
a = ['a', 'b', 'c'] * 100
b = {'a': np.arange(100), 'b': np.ones(100), 'c': np.zeros(100)}
``````

配列が短い時

``````
a = ['a', 'b', 'c']
b = {'a': np.arange(100), 'b': np.ones(100), 'c': np.zeros(100)}
``````

各種実行方法

for文

``````%%timeit
c = np.zeros(100)
for x in a:
c += b[x]
``````

内包表記

``````%%timeit
``````

map

``````%%timeit
``````

np.frompyfunc

``````def d(x):
return b[x]

f = np.frompyfunc(d, 1, 1)
``````
``````%%timeit
np.sum(f(a))
``````

結果

配列が長い時

- for文： `453 µs ± 45.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)`
- 内包表記： `175 µs ± 185 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)`
- map： `189 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)`
- np.frompyfunc： `310 µs ± 316 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)`

配列が短い時

- for文： `6.57 µs ± 61.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)`
- 内包表記： `9.41 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)`
- map： `10 µs ± 224 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)`
- np.frompyfunc： `18 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)`

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What is going on with this article?