LoginSignup
11
3

More than 3 years have passed since last update.

nimとpythonを繋ぐ素敵なnimporter

Last updated at Posted at 2020-07-01

さいつよのnim + pythonを繋ぐモジュール

nimporterというモジュールが感動的だったので紹介します。
いや、紹介自体はn番煎じかもだけど、あんま知られてないっぽいので。
https://github.com/Pebaz/Nimporter
要するに、nimの超高速コードをpythonでインタプリタっぽく動かす奴です。

公式の例を抜粋しますが、nimのコードを下記のように

import nimpy

proc add(a: int, b: int): int {.exportpy.} =
    return a + b

pythonのコードを下記のように

# Nimporter is needed prior to importing any Nim code
import nimporter, nim_math

print(nim_math.add(2, 4))  # 6

書けば、コンパイルが自動的になされてimportされます
いや、マジで実質インタプリタ言語じゃねえか!ってなります。

お約束の速さ比較

敢えておっそい再帰でフィボナッチ数列の計算をさせてみます。
nimのコードは下記。

fibnim.nim
import nimpy
proc fib(n: int): float {.exportpy.}=
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)

pythonの方は下記。

fibpy.py
def fib(n: int) -> float:    
    if n == 1:
        return 0.
    elif n == 2:
        return 1.
    else:
        return fib(n - 1) + fib(n - 2)

...にしても、クッソ似てますね。
この2つをpythonでimportして比べてみましょう。

import fibpy
import nimporter, fibnim
from time import time
cycle = 36
t = time()
print(fibnim.fib(cycle))
print('Time of nim is {} sec'.format(str(time() - t)))
t = time()
print(fibpy.fib(cycle))
print('Time of python is {} sec'.format(str(time() - t)))

>>> 9227465.0
>>> Time of nim is 0.026133298873901367 sec
>>> 9227465.0
>>> Time of python is 3.1436727046966553 sec

1回目はコンパイルの時間がかかるのですが、二回目以降は順当に100倍以上ですね。

そもそもcythonじゃダメなん?

ダメではない。むしろ筆頭候補。cythonも最近はかなり使いやすくなっていて
型ヒント付きpythonをpurepythonモードに食わせるとpythonから変更無しで移行できそうなレベルです。1

import pyximport
pyximport.install()

ってな感じでサクッとインポートできます、優秀です。
(追記。ここ、pyximportの事書いてなくてcythonizeしないとだから面倒いよねって書いてました。間違いです、すみません。)
ただ、cythonは一部でpythonを使う事があるので、
カツカツに最適化する時にprofiling使ってチューニングしていかないといけないので
意外と面倒…という時が無くもない気がします。
その点がnimの強みでしょう。


  1. 実際はチューニング頑張らないと速くならなかったりする 

11
3
4

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
11
3