When Does It Make Sense To Rewrite A Python Module in C?

c, optimization, python

Solution

If you're vector-munging, give numpy a try first. Chances are you will get speeds not far from C if you utilize numpy's vector manipulation functions wisely.

Other than that, your question is very heuristic. If your code is too slow:

- Profile it - chances are you'll be able to improve it in Python

- Use the correct optimized C-based libraries (numpy in your case)

- Try `psyco`

- Try rewriting parts with `cython`

- If all else fails, rewrite in C

Problem

In a game that I am writing, I use a 2D vector class which I have written to handle the speeds of the objects. This is called a large number of times every frame as there are a lot of objects on the screen, so any increase I can make in its speed will be useful. It is pretty simple, consisting mostly of wrappers to the related math functions. It would be quite trivial to rewrite in C, but I am not sure whether doing so will make any significant difference as all it really does is call the underlying math functions, add, multiply or divide. So, my question is under what circumstances does it make sense to rewrite in C? Where will you see a significant speed boost, and where can you see a reasonable speed boost without rewriting an extensive amount of the program?

Original source

Related problems