I Rewrote One Function in Squirrel, Then in C. One Line of Python Was Just as Fast
Description and use
Rewrote a small function from Python to C, integrating it via cffi without manual build steps. Performance gain was minimal, but the workflow became simpler and ready for future C integration.
Problem
Adding a C function to a Python game engine without a build step, while keeping performance and simplicity.
Outcome
The C rewrite eliminated VM overhead and float conversions, but the performance gain was negligible for a three-comparison function. The main benefit was a clean, zero-configuration integration path for future C code.
Workflow
- Write C source (mathutil.c) and header (mathutil.h) with function declaration.
- Configure cffi to load header and source, specifying include dirs and libraries.
- Use functools.cache to trigger rebuild only when source or header changes.
- Import compiled module via c_source and expose clamp function to Python.
- Run engine; C function is called directly, eliminating VM overhead.
- Verify import errors and rebuild if binary mismatches Python version.
- Commit only source files, not build artifacts, and update CI to build on all platforms.
Evidence
I spent two weeks and two language integrations optimizing a function whose body costs less than calling it.
Link the math library on POSIX and not on Windows. MSVC goes looking for m.lib and fails.
- Record date: 2026-09-18T07:31:07.065Z