Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
Nikwin Avatar asked Nov 29 '22 11:11

Nikwin


2 Answers

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:

  1. Profile it - chances are you'll be able to improve it in Python
  2. Use the correct optimized C-based libraries (numpy in your case)
  3. Try psyco
  4. Try rewriting parts with cython
  5. If all else fails, rewrite in C
like image 138
Eli Bendersky Avatar answered Dec 06 '22 10:12

Eli Bendersky


First measure then optimize

like image 29
Martin Beckett Avatar answered Dec 06 '22 10:12

Martin Beckett