I would like to introduce a module called nimporter because it was very moving. No, the introduction itself may be the nth decoction, but it seems that it is not well known. https://github.com/Pebaz/Nimporter In short, it's the guy who runs nim's ultra-fast code in python like an interpreter.
Here's an excerpt from the official example, but the nim code looks like this:
import nimpy
proc add(a: int, b: int): int {.exportpy.} =
return a + b
The python code is as below
# Nimporter is needed prior to importing any Nim code
import nimporter, nim_math
print(nim_math.add(2, 4)) # 6
If you write it, ** it will be compiled automatically and imported **. No, it's really an interpreted language! It will be.
Let's dare to calculate the Fibonacci sequence by recursion. The code for nim is below.
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)
For python, see below.
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)
... But it looks like Kusso. Let's import these two with python and compare them.
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
It takes time to compile the first time, but after the second time, it is 100 times or more.
Not bad. Rather the first candidate. Cython has also become quite easy to use these days If you feed python with type hints to pure python mode, you can migrate from python without any changes. [^ ikou]
[^ ikou]: Actually, if you don't do your best in tuning, it won't be faster.
cythonize -i hoge.py
You can make a module like that, but is it troublesome to have to go back to bash once? Also, cython sometimes uses python, so I feel that there are times when it is unexpectedly troublesome when optimizing for shavings.
Recommended Posts