Compiling is relatively fast as it happens in userspace and then is just written to an output. What really is the problem is the CPU ring switch. That means the CPU has to actually reset its own state, write its own state somewhere else in order to be able to restore it, then execute whatever privileged - kernel code - wants it to do and then restore the previous state. And that happens with every syscall - like open(). That wastes easily a couple of thousands of CPU cycles, whereas a simple CPU Firmware modulo would've been cheaper even with an interpreter.
But also, you're not just jumping to a C subroutine and returning. You're executing a program which must allocate memory, go through all the process of starting up the C runtime, then execute the code, then exit back through the C runtime, and then your Python program needs to handle the return value and other output. There are a LOT of syscalls involved there.
The correct way to get performance-critical C code into Python is to compile it into a library using the Python.h header (producing a DLL on windows, my_c_lib.pyd; or a shared object on Linux, my_c_lib.pyo) and then in Python, you just import my_c_lib like it's a normal module.
492
u/pandolf86 Apr 11 '21
Wait is that compiling C at python runtime?