Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

I Rewrote One Function in Squirrel, Then in C. One Line of Python Was Just as Fast

说明与用途

将一个小函数从 Python 重写为 C,并通过 cffi 无需手动构建即可集成。虽然性能提升不大,但工作流程更简洁,已为未来的 C 集成做好准备。

问题

Adding a C function to a Python game engine without a build step, while keeping performance and simplicity.

结果

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.

工作流

  • 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.

证据

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.

来源

  • 记录日期: 2026-09-18T07:31:07.065Z