Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of using long vs. int in Python

I need to manipulate large numbers in Python that fit into 64 bits. Currently, my code is running on a 64-bit platform but there is small but distinct possibility that it will have to run on a 32-bit platform. Consequently, I would prefer to use long type to represent my numbers. I understand there is a performance impact for using long over int type. How bad is it? I'll be performing a lot of divisions and multiplications on them, but the results should all fit into 64 bits, too.

like image 959
VladLosev Avatar asked Jan 12 '12 01:01

VladLosev


2 Answers

If you're going to be doing a lot of heavy number crunching, have a look at "numpy".

like image 108
MRAB Avatar answered Oct 21 '22 20:10

MRAB


If your program does a lot of numerical computations - to a point that performance matters, you should profile it, and have the numerical part running in native code. You should not have to worry if internally the numbers are Python "integers" or "long" - so much that Python 3 removes the type difference.

There are several approaches for it, from using numpy, cython, a C extension, running your program using pypy instead of the standard cpython, and even take a look at corepy - what you should not do is to have a numeric intensive task running in pure python if performance is an issue there. Event he most complicated of these - creating a C extension in the form of a single function that just perform the calculations is simple enough to be well worth the performance gains in this case.

like image 37
jsbueno Avatar answered Oct 21 '22 22:10

jsbueno