Can I rewrite my expensive pygame functions in C?

Is it possible for me to find expensive functions (e.g. A * pathfinding) in my pygame game and rewrite them as extensions, as indicated here ?

Is there a speed advantage for this? Is there a better (python) solution?

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

+4
source share
2 answers

Is there a speed advantage for this?

It is impossible to say without knowing exactly what you are doing, but the general answer is "very likely."

Is there a better (python) solution?

Again, this cannot be said. Better than that?

If you work with numeric arrays, then the first step should probably be to use NumPy .

After you have done this, there are several ways to speed up the process, in addition to coding extensions, in the original C:

  • Cython : write extensions in a language like Python;
  • numexpr : A mechanism for quickly evaluating array expressions.

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

+8
source

You can use cProfile to find the most expensive functions in your code. I'm sure you will see a performance improvement after moving some code to C. From my tests, this could be anything: from a 2x improvement to 200x depending on your code.

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

Here is a great tutorial on various methods that you can use to optimize your code, including profiling and Cython:

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

+4
source

Source: https://habr.com/ru/post/1414141/


All Articles