Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bignum implementation that has efficient addition of small integers

I have been using python's native bignums for an algorithm and decided to try and speed it up by converting it to C++. When I used long longs, the C++ was about 100x faster than the python, but when I used GMP bindings in C++, it was only 10x faster than the python (for the same cases that fit in long longs).

Is there a better bignum implementation for doing a large number of small additions? For example, we have a big number N we'll be adding a lot of little +1, +21, +1, etc. and every once and a while adds another big number M?

like image 537
sligocki Avatar asked Nov 05 '22 18:11

sligocki


1 Answers

The GMP library itself has a fast short integer add to MPZ routine

void mpz_add_ui (mpz_t rop, mpz_t op1, unsigned long int op2)

I don't know whether gmpy uses that, but if it does try adding a normal python int to an mpz vs adding an mpz to mpz and see if it is quicker.

Edit

I tried a bit of benchmarking and found it doesn't make any difference

$ python -m timeit -c 'from gmpy import mpz
> a=mpz(10**1000)' 'a+1'
100000 loops, best of 3: 5.4 usec per loop

$ python -m timeit -c 'from gmpy import mpz
a=mpz(10**1000); b=mpz(1)' 'a+b'
100000 loops, best of 3: 5.5 usec per loop

So I guess gmpy doesn't use mpz_add_ui as I really would expect that to be a lot quicker.

like image 197
Nick Craig-Wood Avatar answered Nov 11 '22 20:11

Nick Craig-Wood