done is better than perfect

自分が学んだことや、作成したプログラムの記事を書きます。すべての記載は他に定める場合を除き個人的なものです。

Pythonでのanyの速度

Pythonにはanyallといった便利な関数があります。

こちらのサイトに、

しかし特にany関数では、ジェネレータ式を使用した方がパフォーマンスが良いと思う。

と書いてあったので、せっかくなのでipythonに慣れることも兼ねて簡単に計測してみました。

結果は以下です。

Python 3.4.1 (default, May 19 2014, 13:10:29) 
Type "copyright", "credits" or "license" for more information.

IPython 2.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
Using matplotlib backend: MacOSX

In [1]: test_list = [2 * i for i in range(1000)]

In [2]: timeit any([v > 1000 for v in test
test       test_list  

In [2]: timeit any([v > 1000 for v in test_list])
10000 loops, best of 3: 178 µs per loop

In [3]: timeit any(v > 1000 for v in test_list)
100000 loops, best of 3: 13.1 µs per loop

オーダーが1つ違いますね。ジェネレータで書ける時はジェネレータで書きましょう!