LoginSignup
9

More than 5 years have passed since last update.

[python] pypyで遊んでみる

Posted at

pypy

pypyはpythonを早く実行できるすごいやつ。
今回はpyenvでインストールしたpypy3を使ってみます。

インストール

とりあえずインストールしてみる。

pypy.install
$ pyenv install pypy3-2.4.0
$ pyenv shell pypy3-2.4.0
$ $ pypy
Python 3.2.5 (b2091e973da6, Oct 19 2014, 18:30:58)
[PyPy 2.4.0 with GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)] on darwin

入りました、pypy3-2.4.0のpythonのバージョンは3.2.5のようです。

簡単な速度テスト

pypy3-2.4.0とpython3.2.5の速度をとりあえず比較してみます。

簡単なコード、シンプルに$10^{10}$回イテレーションを回してみる

simple_speed_test.py
import time
def time_test(func):
    def _time_test():
        a = time.time()
        func()
        return time.time() - a
    return _time_test

@time_test
def speed_test():
    for _ in range(10**10):
        pass

if __name__ == "__main__":
    print(speed_test())

まず、python3.2.5から

test-1-python3.2.5
$ python --version
Python 3.2.5
$ python speed_test.py 
228.04035305976868 

普通におそいです。
次にpypy3-2.4.0で実行してみます。

test-1-pypy3-2.4.0
$ pypy --version
Python 3.2.5 (b2091e973da6, Oct 19 2014, 18:30:58)
[PyPy 2.4.0 with GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)]
$ pypy speed_test.py 
8.809449911117554

すごく早いです。

次に、ファイル読み込みをしてみます。

単純に、csvファイルを一行づつ読みこむだけの作業してみます。
1600000行、200MBのものを読み込んでみます。

speed_test-2.py
@time_test
def load_text():
    for line in open('sample.csv'):
        pass 

if __name__ == '__main__':
  print(load_text())

まず、python3.2.5から、

test-2-python3.2.5
$ python --version
Python 3.2.5
$ python speed_test.py 
0.9221069812774658

結構早いです。。。
次にpypyで実行してみます。

test-2-pypy3-2.4.0
$ pypy --version
Python 3.2.5 (b2091e973da6, Oct 19 2014, 18:30:58)
[PyPy 2.4.0 with GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)]
$ pypy speed_test.py 
2.5766420364379883

今度はpypyの方が遅いですね。
こういった処理は苦手なようですね。

まとめ

pypyは単純な計算をするときは早いようです。
自分よりちゃんとテストしてる人がいるので気になる人がいれば参考に
[Python][PyPy]PyPy3 2.4.0を使ってみた

しかし、モジュールが使えない場合があります。
numpy等はこのバージョンでは使えないっぽいです。
2系のpypyではnumpyも使えるようですが、試していません。

頑張れる人は、Cythonで書くのが良いと思います。

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
9