73
Pythonの実装系総ざらい

Pyconjp2014_implementations

Embed Size (px)

DESCRIPTION

Introduction to Python Implemetations

Citation preview

Page 1: Pyconjp2014_implementations

Pythonの実装系総ざらい

Page 2: Pyconjp2014_implementations

お前誰よ• @Masahito

• P2P,File,Transfer,Engineer,at,Skeed,Co.,Ltd.

• I,work,with,Scala,&,JVM(Sorry!)

• We,use,Python,for,ImplementaJon,the,CLI,,and,,to,deploy,the,P2P,client(fabric,etc)

Page 3: Pyconjp2014_implementations

PyCon&Singapore&2014でLTしてきました

Page 4: Pyconjp2014_implementations

みなさんの反応

Page 5: Pyconjp2014_implementations
Page 6: Pyconjp2014_implementations

今年のPyConJPのテーマ

Page 7: Pyconjp2014_implementations

Pythonで再発見

Page 8: Pyconjp2014_implementations

伝えたいこと• いろんな処理系の紹介

• メリット/デメリットよりも使うシーン

• 言葉がたくさん出てくるので名前だけでも覚えていただれば

• Python)is)Glue

• 用途にあった言語を使おう

Page 9: Pyconjp2014_implementations

伝えないこと• Pythonの仕様

• 各実装系の細かい仕様の差異

• 実際にどんなところで使われてる?

Page 10: Pyconjp2014_implementations

今回ご紹介する実装• CPython(2.X-and-3.X)

• Jython

• IronPython

• PyPy

• Pyston

Page 11: Pyconjp2014_implementations

Pythonの特徴かるくまとめ

Page 12: Pyconjp2014_implementations

Pythonとは1.広範囲に及ぶ標準ライブラリとサードパーティのモジュール

2.拡張とモジュールはC/C++で書くのが容易

3.アプリケーションに組み込んでスクリプトインタフェースとして利用することが可能

Page 13: Pyconjp2014_implementations

クエスチョン1. C言語より速く動作する?

2.静的型付け?

Page 14: Pyconjp2014_implementations

GlueとしてのPython

Page 15: Pyconjp2014_implementations

CPython

Page 16: Pyconjp2014_implementations

CPython• CPython2(2.7.8)

• CPython3(3.4.1)

• Python2プログラミング言語の最も広く用いられている標準の実装である。2CPython2は2C言語で記述されている。

• Pythonでできないことを、もしくは低レベルコードの高速性が必要になった場合は、C/C++で拡張モジュールを作成

Page 17: Pyconjp2014_implementations

ctypes

!ctypes!は!Python!のための外部関数ライブラリです。このライブラリ!は!C!と互換性のあるデータ型を提供し、動的リンク/共有ライブラリ内の関数呼び出しを可能にします。動的リンク/共有ライブラリを純粋な!Python!でラップするために使うことができます。from%h'p://docs.python.jp/2/library/ctypes.html

Page 18: Pyconjp2014_implementations

 例!dllをたたく#include "dll.h"#include <Windows.h>

BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpReserved) {

switch(fdwReason) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; }

return TRUE;}

// 単純な加算。DLL_EXPORT int __add(const int x, const int y) { return x + y;}

Page 19: Pyconjp2014_implementations

from ctypes import windll

lib = windll.LoadLibrary("dll.dll");if (lib.__add(1,2) != 3): print("error!")else: print("ok")

Page 20: Pyconjp2014_implementations

CPython• Python/C*API

• Pyrexh0p://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

• Cythonh0p://cython.org/

• boost.pythonh0p://www.boost.org/doc/libs/1560/libs/python/doc/

Page 21: Pyconjp2014_implementations

Python/C)API#include <Python.h>

static PyObject* helloworld(PyObject* self){ return Py_BuildValue("s", "Hello, Python extensions!!");}

static char helloworld_docs[] = "helloworld( ): Any message you want to put here!!\n";

static PyMethodDef helloworld_funcs[] = { {"helloworld", (PyCFunction)helloworld, METH_NOARGS, helloworld_docs}, {NULL}};

void inithelloworld(void){ Py_InitModule3("helloworld", helloworld_funcs, "Extension module example!");}

Page 22: Pyconjp2014_implementations

numpy関連ちょっとそれるけどnumpyでのスピードアップ用に• numbah(p://numba.pydata.org/

ってのもあります。バックエンドはLLVMPY

h'p://www.llvmpy.org/

Page 23: Pyconjp2014_implementations

例from numba import jitfrom numpy import arange

# jit decorator tells Numba to compile this function.# The argument types will be inferred by Numba when function is called.@jitdef sum2d(arr): M, N = arr.shape result = 0.0 for i in range(M): for j in range(N): result += arr[i,j] return result

a = arange(9).reshape(3,3)print(sum2d(a))

Page 24: Pyconjp2014_implementations

cpython3• C#APIのInterfaceが少し変わった

• むしろめんどいのはString/Unicode#=>#Unicode/Byteなところ

Page 25: Pyconjp2014_implementations

って口で言うだけだとあれですねここでコード例をひとつ前に自分で書いたやつを見せておきます。• pyuv

Pythonでのlibuvのwrapper1module.

asynchronous1I/O1にフォーカスしたマルチプラットフォームライブラリでnode.jsで使われてる。

Page 26: Pyconjp2014_implementations

Python#ifdef PYUV_PYTHON3static PyModuleDef pyuv_fs_module = {PyModuleDef_HEAD_INIT,"pyuv.fs", /*m_name*/NULL, /*m_doc*/-1, /*m_size*/FS_methods, /*m_methods*/};#endif

#ifdef PYUV_PYTHON3module = PyModule_Create(&pyuv_fs_module);#elsemodule = Py_InitModule("pyuv.fs", FS_methods);#endif

Page 27: Pyconjp2014_implementations

もっと詳しく知りたい方• Python(インタプリタの拡張と埋め込みh)p://docs.python.jp/3/extending/index.html

• Python(3(への拡張モジュール移植h)p://docs.python.jp/3.4/howto/cpor<ng.html

Page 28: Pyconjp2014_implementations

Jython

Page 29: Pyconjp2014_implementations

Jython

1. h$p://www.jython.org/

2.最新は12.5.3/12.5.4rc1/12.71beta3

3. JVM上で動作するPython

Page 30: Pyconjp2014_implementations

Jythonの特徴• Javaのライブラリが使える.GUIとかも

• コンパイル)/)実行という手順を踏まずに、アイデアやAPIの実験および調査を簡単に実行できる

• No)Global)Interpreter)Lock[やばい]

Page 31: Pyconjp2014_implementations

例:"GUIアプリケーションfrom javax.swing import JButton, JFrame

frame = JFrame('Hello, Jython!', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (300, 300) )

def change_text(event): print 'Clicked!'

if __name__=="__main__": button = JButton('Click Me!', actionPerformed=change_text) frame.add(button) frame.visible = True

Page 32: Pyconjp2014_implementations
Page 33: Pyconjp2014_implementations

例:"classpath"の設定foo.jarを使う$ export CLASSPATH=$CLASSPATH:foo.jar; jython foo.py

Page 34: Pyconjp2014_implementations

invokeDynamic

一言で言うのは難しいんだけどこれに対応してると、JVM上で動く動的型付け言語でもJavaの呼び出しと同じ最適化をかけてくれると思ってください。言語処理系が自分で最適化ではなく、JVMにお任せできる

Page 35: Pyconjp2014_implementations

今のところinvokeDynamic対応はまだらしいh"ps://wiki.python.org/jython/RoadMap

Towards(v3.3(Use(of(Java(7(invokedynamic:(Jim?(

いつか実装されるのかも

Page 36: Pyconjp2014_implementations

Iron%Python

Page 37: Pyconjp2014_implementations

Iron%Python

1. h$p://ironpython.net/

2.最新は02.7.4

3. .NET0Framework0上で動作するPython

4. Python0Tools0fo0VisualStudioで導入できる

Page 38: Pyconjp2014_implementations

DLR• 動的言語を.NET&Framework上に実装するために使われる。

• DLR&は既存のCLRと.NET&Framework仮想マシン上に構築されている.

• 現在の最新版であるIronPython&2.x系列は.NET&4に対応し、DLR(動的言語ランタイム)上に実装されている

Page 39: Pyconjp2014_implementations

例:空のウィンドウimport clrclr.AddReferenceByPartialName("System.Windows.Forms")clr.AddReferenceByPartialName("System.Drawing")import Systemfrom System.Windows.Forms import Formfrom System.Drawing import Size

form = Form()form.Size = Size(300,200)form.Text = "Hello World!"

System.Windows.Forms.Application.Run(form)

h"p://www.yasundial.org/ironpython/book.html

Page 40: Pyconjp2014_implementations

Pythonで書いたんだしこのまま早くなると言いなぁ

Page 41: Pyconjp2014_implementations

そう思うこと多いよね

Page 42: Pyconjp2014_implementations

ここからははやく動かすのを考えた処理系の話をしますね

Page 43: Pyconjp2014_implementations

PyPy

Page 44: Pyconjp2014_implementations

PyPy

1. h$p://pypy.org/

2. the/Python2.7/compa6ble/release/—/PyPy/2.3.1

3. the/Python3.3/compa6ble/release/—/PyPy3/2.3.1/

4. PyPyは、Armin/Rigoが開発した、PythonのJIT特殊化コンパイラである/Psyco/の後継プロジェクト

5. Pythonにいくつかの制約を加えた言語であるRPythonで記述

6.セルフホスティング

Page 45: Pyconjp2014_implementations

PyPy#とは?

2つの側面がある1. インタプリタ型言語のインタプリタを実装するためのツールセット2. このtoolchainを使用した Python の実装

Page 46: Pyconjp2014_implementations

toolcahinを利用した他の実装• Topaz'(an(implementa/on(of(the(Ruby(programming(language(using(PyPy(technology.h<ps://github.com/topazproject/topaz

• HippyVM('(an(implementa/on(of(the(PHP(language(using(PyPy(technology.h<p://hippyvm.com/

Page 47: Pyconjp2014_implementations

JIT• PyPyと言えば速さ

• Just(In(Time(Compiler実行時に処理の流れを解析して最適化,(JSのV8とかのが有名か

• JIT(documenth;p://pypy.readthedocs.org/en/latest/jit/

• 流行りのJITコンパイラは嫌いですか?(

h;p://www.longsleeper.com/pypyadvent11

Page 48: Pyconjp2014_implementations

いま行われていること1. PyPy3

2. STM(So,ware1Transac5onal1Memory)GILがとれるかも

3. numpypy

Page 49: Pyconjp2014_implementations

おまけ• PyPy$jaってユーザグループがございますh"ps://groups.google.com/forum/#!forum/pypy4ja

Page 50: Pyconjp2014_implementations

Pyston

Page 51: Pyconjp2014_implementations

Pyston• あのGuidoが所属してるDropboxで作られてる実装

• Python12.X互換(未来のどこかで3.X対応するらしい)

• LLVMでビルドしてLLVM1IRに変換して実行

• Unladen1swallowのことは忘れよう

• 0.2が昨日出たorz

Page 52: Pyconjp2014_implementations

Pyston• 現状binaryは配られてないので自分でbuild

• LLVMからビルドするよ!

• LLVM/IRに変換して実行

Page 53: Pyconjp2014_implementations

Roadmapv0.1:&released&4/2/2014

• Focus'was'on'building'and'valida1ng'the'core'Python8to8LLVM'JIT'infrastructure.

• Many'core'parts'of'the'language'were'missing.

Page 54: Pyconjp2014_implementations

v0.2:&released&9/11/2014

• Many&new&features:

• Excep3ons

• Class&inheritance,&metaclasses

• Basic&na3ve&C&API&support

• Closures,&generators,&lambdas,&generator&expressions

• Default&arguments,&keywords,&*args,&**kwargs

• Longs,&and&integer&promo3on

• Mul3threading&support

Page 55: Pyconjp2014_implementations

v0.3:&current&series

• Goal&is&to&improve&performance,&informed&by&our&behavior&on&real&benchmarks.

Page 56: Pyconjp2014_implementations

速度比較

Page 57: Pyconjp2014_implementations

速度比較• Python(v2.7.3

• PyPy(v2.2.1

• Pyston(v0.1(2014/04/15)

Page 58: Pyconjp2014_implementations

再帰import time

def fib(n): if n < 2: return n return fib(n - 2) + fib(n - 1)

if __name__ == "__main__": for x in range(3): fib(3)

start = time.time() result = fib(38) timespan = time.time() - start print(result) print (timespan)

Page 59: Pyconjp2014_implementations
Page 60: Pyconjp2014_implementations

ループimport time

def fib(n): value = 0 f1, f2 = 1, -1 for i in range(n+1): value = f1 + f2 f2 = f1 f1 =value

return value

if __name__ == "__main__": for x in range(3): fib(3)

start = time.time() result = 0 for x in range(0,5000): result = fib(38) timespan = time.time() - start print(result) print (timespan)

Page 61: Pyconjp2014_implementations
Page 62: Pyconjp2014_implementations

One$more$thing...

Page 63: Pyconjp2014_implementations

Pyston'0.2での結果

Page 64: Pyconjp2014_implementations

• Python(v2.7.6

• PyPy(v2.3.1

• Pyston(v0.2(2014/09/11)(new!

Page 65: Pyconjp2014_implementations
Page 66: Pyconjp2014_implementations
Page 67: Pyconjp2014_implementations

(つд⊂)ゴシゴシ→(;゚%Д゚)傾向が変わっていない...

Page 68: Pyconjp2014_implementations

今後に期待

Page 69: Pyconjp2014_implementations

組み込み用ではMicroPythonってのがある

Page 70: Pyconjp2014_implementations

この後お話が聞けるので興味のある方は[Conference)Room)1]へGo!

Page 71: Pyconjp2014_implementations

まとめ• PythonはGlueとして使うと便利

• Pythonの実行を効率化しようとしてる実装は複数存在する

• PyPyは楽しいよ

• Pystonは今後に期待

Page 72: Pyconjp2014_implementations

Pythonを再発見できたでしょうか?

Page 73: Pyconjp2014_implementations

Ques%on?