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