summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorTim Peters <tim@python.org>2013-10-05 21:55:38 (GMT)
committerTim Peters <tim@python.org>2013-10-05 21:55:38 (GMT)
commit9259c21a63ea5c342936a18317d455f747248b2f (patch)
treeda9790946a8a4436473be259b61a04dd193c21de /Objects
parente898153c0f64f3e618c619523bcee90500c3b322 (diff)
parent81a93159d7a4bfc6a6d06f44528d9d17a8c634c2 (diff)
downloadcpython-9259c21a63ea5c342936a18317d455f747248b2f.zip
cpython-9259c21a63ea5c342936a18317d455f747248b2f.tar.gz
cpython-9259c21a63ea5c342936a18317d455f747248b2f.tar.bz2
Issue #19171: speed some cases of 3-argument long pow().
Reduce the base by the modulus when the base is larger than the modulus. This can unboundedly speed the "startup costs" of doing modular exponentiation, particularly in cases where the base is much larger than the modulus. Original patch by Armin Rigo, inspired by https://github.com/pyca/ed25519. Merged from 3.3.
Diffstat (limited to 'Objects')
-rw-r--r--Objects/longobject.c14
1 files changed, 10 insertions, 4 deletions
diff --git a/Objects/longobject.c b/Objects/longobject.c
index 8748706..876cd19 100644
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -3878,10 +3878,16 @@ long_pow(PyObject *v, PyObject *w, PyObject *x)
goto Done;
}
- /* if base < 0:
- base = base % modulus
- Having the base positive just makes things easier. */
- if (Py_SIZE(a) < 0) {
+ /* Reduce base by modulus in some cases:
+ 1. If base < 0. Forcing the base non-negative makes things easier.
+ 2. If base is obviously larger than the modulus. The "small
+ exponent" case later can multiply directly by base repeatedly,
+ while the "large exponent" case multiplies directly by base 31
+ times. It can be unboundedly faster to multiply by
+ base % modulus instead.
+ We could _always_ do this reduction, but l_divmod() isn't cheap,
+ so we only do it when it buys something. */
+ if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
if (l_divmod(a, c, NULL, &temp) < 0)
goto Error;
Py_DECREF(a);