I Rewrote One Function in Squirrel, Then in C. One Line of Python Was Just as Fast.
I maintain a 2D game engine in Python called ABS Engine. Last week I decided it needed C. Not because anything was slow. That is the embarrassing part. I wanted to drop a .c file into a folder and call it from Python with no build step anyone has to know about. It took 197 lines, most of them docstrings. The first function I moved over was clamp . Keep a number between a low and a high. Three…
In the ABS Engine, a 2D game engine, a Python programmer rewrote the clamp function, initially in Python, then in Squirrel, and finally in C. The function's purpose was to constrain a number within a specified range. The C version of clamp, containing only three comparisons, proved to be as fast as the Python and Squirrel implementations.
The Python implementation called the function with three float() conversions, while the C version required only a call without the conversions. The C function was implemented in mathutil.h, and the CFFI library was used to load the compiled C code into Python. This approach eliminated the need for a build step, and the programmer could simply edit the C code, run the program, and see the changes take effect immediately.
The programmer aimed to streamline the process of incorporating C code into the Python game engine, allowing for seamless integration without the burden of build configurations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.