Python is fast enough for most of what I do with it. Then one function ends up in a hot loop, the profiler points straight at it, and I have to decide what to do about it.
The usual answers are heavy. Rewrite the service in Go. Write a C extension. Learn Cython and its build setup. I wanted to see how little it could take, so I put together a small experiment called py-nim. It is the same naive recursive Fibonacci written twice, once in Python and once in Nim, and the Nim version is compiled into a module that Python imports like any other.
There is no C to write, no ctypes and no cffi. It comes down to one pragma on one proc.
What I measured
I ran fib(35) three ways: plain Python, Python calling the Nim module, and Nim as a standalone binary.
| fib(35) | time | vs Python | |
|---|---|---|---|
| Python | 9227465 | 0.539 s | 1x |
| Python calling Nim | 9227465 | 0.025 s | 22x |
| Nim, standalone binary | 9227465 | 0.013 s | 41x |
That was Python 3.12.1, Nim 2.2.12 and gcc 11.4 on an ordinary Linux laptop. Your numbers will be different. The ratios are what matter.1
The middle row is the one I care about. The work runs at compiled speed, but the call still starts and ends in Python, so nothing else in the program has to change.
Twelve milliseconds is what you give up for staying in Python, and it buys back everything else Python is there for.
The last row is only there as a ceiling. The standalone binary beats the same code inside the module because a shared library is compiled as position independent code, and a recursion this tight notices the difference. I would not ship that version. It throws Python away to save twelve milliseconds.
How it works
The Python baseline
This is the slowest reasonable way to compute the number, on purpose:
def fib(n: int) -> int:
if n <= 2:
return 1
return fib(n - 1) + fib(n - 2)
The same function in Nim
Here is the whole Nim side:
import nimpy
proc fib(n: int): int {.exportpy.} =
if n <= 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
{.exportpy.} comes from nimpy. It writes the CPython glue for you: the module init function, the argument unpacking and the conversion of the return value. I did not have to touch any of that.
Building the module
One command compiles it into a shared library that CPython imports by its ordinary rules:
nim c -d:release --mm:orc --app:lib --out:fib_nimpy.so fib_nimpy.nim
The one thing to get right is naming. Three names have to agree:
- the Nim file,
fib_nimpy.nim - the shared library,
fib_nimpy.so - the name you import in Python,
fib_nimpy
nimpy generates PyInit_fib_nimpy from the module name, and that is the symbol CPython looks for when it loads the library. If one of the three is off, the import fails.
Calling it from Python
from fib_nimpy import fib
fib(35)
That is all of it. The two Python runners in the repository are identical apart from where fib comes from, so the diff between them is the entire integration.
Try it yourself
You need Python 3.10 or newer, Nim 2.0 or newer with nimble, and a C compiler, because Nim compiles through C.2
make deps # fetch nimpy
make # build fib_nimpy.so and the standalone fib_nim binary
make bench # run all three, side by side
make bench takes the Fibonacci index from N, which defaults to 35. Be careful raising it. The cost is exponential, and it is the pure Python row that pays for it. Each step up multiplies the work by about 1.6, so fib(40) takes roughly eleven times longer than fib(35).3
When I would do this
- Profile first. The slow part is often somewhere other than where I expected, and porting the wrong function buys nothing.
- Keep the boundary small. Every call from Python into Nim converts its arguments and its result. One call that does a lot of work wins. A million tiny calls may not.
- Build the module in CI. Nobody on the team should need a Nim toolchain on their laptop just to run the service.
I would rather keep one compiled function behind a plain import than run a second service next to the first. So that is where I start, and I only reach for something bigger when the measurements say I have to.
Footnotes
-
Every row comes from the same run of
make bench, so you can reproduce the table on your own machine with one command. ↩ -
CI builds the project on Nim 2.2.12 and Python 3.13, so those two versions are the ones known to work together. ↩
-
fib(47)is the value this demo used to hardcode. In pure Python it takes about three hundred times longer thanfib(35). ↩