pycryptodome icon indicating copy to clipboard operation
pycryptodome copied to clipboard

Improve speed of GCD, size, inverse

Open jneb opened this issue 4 years ago • 8 comments

Apply the following optimisations that use builtin C code where available: Since Python 2.7 (i.e. always), the length of an integer can be computed with .bit_length() Since Python 3.8, the inverse of a mod b can be computed with pow(a, -1, b) Since Python 3.5, there is a gcd operation in the math module

jneb avatar Nov 30 '20 08:11 jneb

Strange. The errors are all on python 2.6. I thought this wasn't supported anymore. Anyway, I'll make a fix to make it work even if bit_length is not available.

jneb avatar Nov 30 '20 12:11 jneb

Python 2.6 CI tests are just a leftover and will be soon be removed.

Legrandin avatar Nov 30 '20 12:11 Legrandin

In that case, it is better to pull 001eb877c3e615804fe41cb59120d367ee65ef29 instead of 249ce5540caa080abf381a6c7839274980ccd8a9, saving seven lines of code and a try block :-).

jneb avatar Nov 30 '20 12:11 jneb

if speed's the reason, shouldn't the code rather define different methods, so that the exceptions aren't thrown and caught every time the functions are called, but only once, during module load?

tomato42 avatar Nov 30 '20 23:11 tomato42

Good point. I went for readability, and the fact that this solution already does 95% of the gain that you could get. But indeed, a load time check would give you a few percent speedup. I should have a look at exactly where these routines are called to see if it is worth the extra effort.

jneb avatar Dec 01 '20 06:12 jneb

Let's see if this works. If it does, we'll get incredible speed for size and GCD as they contain no Python code whatsoever :-)

jneb avatar Dec 01 '20 15:12 jneb

Sorry, I meant checking for negative numbers before calling .bit_length() would really slow the code down.

jneb avatar Dec 01 '20 15:12 jneb

So this is all works and calls the native routines directly for size and GCD!

jneb avatar Dec 02 '20 09:12 jneb

Almost all changes are merged so I close it. Still keeping the test for negative number when counting bits.

Legrandin avatar Dec 12 '22 21:12 Legrandin