Can I rewrite my expensive pygame functions in C?

Question:

Is it possible for me to find the expensive functions(for example, A* pathfinding) in my pygame game and rewrite them as extensions as outlined here?

Is there a speed benefit to doing so? Is there a better (python) solution?

I ask this question because I have just started learning C for unrelated reasons, when it occured to me this might be a good idea when I go back to Python and pygame.

Asked By: talloaktrees

||

Answers:

Is there a speed benefit to doing so?

It’s impossible to say without knowing what it is exactly that you’re doing, but the general answer is "very likely".

Is there a better (python) solution?

Again, it is impossible to say. Better than what exactly?

If you are working with numerical arrays, then the first step should probably be to use NumPy.

Once you’ve done that, there are multiple avenues for speeding things up other than coding extensions in raw C:

  • Cython: write extensions in a Python-like language;
  • numexpr: fast evaluation engine for array expressions.

Finally, if you do find yourself writing C or C++ extensions, consider using SWIG or Boost.Python.

Answered By: NPE

You can use cProfile to find most expensive functions in your code. I’m pretty sure you will see a performance improvement after moving some of your code to C. From my tests it can be anything from 2x to 200x improvement depending on your code.

The easiest way to achieve this would be to move your expensive functions into separate modules, add variable declarations and compile them with Cython. You can then import them into your main program as they were python modules.

Here’s a great tutorial on different methods you can use to optimise your code including profiling and Cython:

http://ianozsvald.com/HighPerformancePythonfromTrainingatEuroPython2011_v0.2.pdf

Answered By: jaho