Home > Enterprise >  Python speed of dividing by 10 and 2
Python speed of dividing by 10 and 2

Time:10-08

so i’m making a simulation (billiard) in Python that needs to do a lot of updates per second. I know that division (or multiplying by decimal) is one of the slower operations. I was just wondering if that only goes for more “abstract” divisions (ex: ‘173/82’) or if it also goes for “easier” divisions, halving float or dividing by 10.

For extra info, it is for microstepping (getting a more accurate point of collision) so I’ll be dividing the speed. If it is costly to divide by 2 and 10, I’m thinking about precalculating the smaller speeds (on change of the balls speed), but please do suggest if there might be a better way. Thanks for reading:)

CodePudding user response:

Python is a very high level language which abstracts away floating point numbers as full objects. This kind of micro-optimization does not make sense in plain Python code.

If you are down to the algorithm you have to optimize in a few plain operations, one of the steps you could take is to promote the function where the calculation is to cython - it will feature the same syntax as Python and be callable from ordinary Python code, but will be able to use the native CPU floating point implementation for the operations.

If the results are to be consumed from and go into an array, you won't even have the language overhead of converting the value to a Python float instance or each data point.

CodePudding user response:

Best way is to try it, just write a few lines of test code and loop over it a few million times. That's the beauty of Python, you can try things quickly.

Under the covers, the Python interpreter is doing a lot of work and the actual division itself will likely be a small component of the time.

Once the algorithm is right, you might try writing custom functions or classes for Python, in C. I've done this for Monte-Carlo simulation that has to handle millions of events per second.

  • Related