Speed ​​up Python code with Nim

Hello, Khabrovites. In anticipation of the start of the "Python Developer. Basic" course, we have prepared a translation of an interesting article for you. We also invite you to the open webinar "Career for" Python Developer. Basic "".






Python β€” , . , , Python.  , , . Nim.





Nim?

Nim – , , - . Nim , Python, , Lisp. Python, Nim , C .





Nim

Nim, . nim-lang.org.





, Nim. -, , hello.nim, . :





static:
    echo("Hello, world!")
      
      



, :





nim compile hello.nim
      
      



! Β«Hello, World!Β». Nim .





Nim Python

Nim nimpy



nimporter



, Python.  pip install nimporter



. .





Nim, , , n- .





Benchmark 3 : 





  • main.py



    β€” ,





  • nmath.nim



    β€” fib



    Nim





  • pmath.py



    β€” fib



    Python





fib Python:





def fib(n):
    if n == 0:
        return 0
    elif n < 3:
        return 1
    return fib(n - 1) + fib(n - 2)
      
      



nmath.nim



. nimpy



:





import nimpy
      
      



Python, ? :





import nimpy

proc fib(n: int): int {.exportpy.} =
    if n == 0:
        return 0
    elif n < 3:
        return 1
    return fib(n-1) + fib(n-2)
      
      



fib



proc



. , (, ?) {.exportpy.}



Nim, Python. , Python.





main.py :





import nimporter
from time import perf_counter
import nmath  # Nim imports!
import pmath
print('Measuring Python...')
start_py = perf_counter()
for i in range(0, 40):
    print(pmath.fib(i))
end_py = perf_counter()

print('Measuring Nim...')
start_nim = perf_counter()
for i in range(0, 40):
    print(nmath.fib(i))
end_nim = perf_counter()

print('---------')
print('Python Elapsed: {:.2f}'.format(end_py - start_py))
print('Nim Elapsed: {:.2f}'.format(end_nim - start_nim))
      
      



!

nimporter



Nim Python, , . , ?





, python main.py



, !





Python Elapsed: 33.60
Nim Elapsed: 1.05
      
      



, , Nim Python. Nim 30 , , . Nim, .





, ! , . , .






"Python Developer. Basic".



demo- Β« : map(), filter() zip()Β».








All Articles