LoginSignup
13
12

More than 5 years have passed since last update.

PythonでNimの関数を使う

Last updated at Posted at 2018-01-05

はじめに

Nimが結構速くて良さげなのでNimで書いた処理をPythonで使ってみます。

準備

MacでのNimのインストールは

$ brew install nim

でできます。

コンパイルは

$ nim c test.nim

本題

今回はフィボナッチ数を求める関数を作ります。

test.nim
proc fib_nim(n: int): int {. exportc, dynlib .} =
  if n < 2:
    return n
  else:
    return fib_nim(n - 1) + fib_nim(n - 2)

{. exportc, dynlib .} は共有ライブラリ化するのに必要なようです。

保存して共有ライブラリにコンパイル

$ nim c --app:lib -d:release test.nim

コンパイルするとlibtest.dylibというファイルができているので、それをPythonで利用する。

main.py
from ctypes import *

def fib_nim(n):
    test_lib = CDLL('./libtest.dylib')
    return test_lib.fib_nim(n)

print(fib_num(40))


実行してみると

$ python main.py
102334155

速度比較

Pythonで書いたフィボナッチ数を求める処理と比較してみます。

fib_py.py
def fib_py(n):
  if n < 2:
    return n
  else:
    return fib_py(n - 1) + fib_py(n - 2)

print(fib_py(40))


fib_py.py の実行速度は

$ time python fib_py.py
102334155
python fib_py.py  52.65s user 0.15s system 99% cpu 52.977 total


Nimで作成した共有ライブラリを用いた場合

$ time python main.py
102334155
python main.py  0.70s user 0.07s system 94% cpu 0.812 total

最後に

Nimは速度かなり出るので使い所ありそうって感じです。

13
12
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
13
12