diff options
author | Victor Stinner <vstinner@python.org> | 2024-01-10 15:38:56 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-01-10 15:38:56 (GMT) |
commit | 93930eaf0acd64dc0d08d58321d2682cb019bc1a (patch) | |
tree | 3b1c444f2f7cb1ee7260e499800c5cda0ddc388a /Modules/mathmodule.c | |
parent | 66363b9a7b9fe7c99eba3a185b74c5fdbf842eba (diff) | |
download | cpython-93930eaf0acd64dc0d08d58321d2682cb019bc1a.zip cpython-93930eaf0acd64dc0d08d58321d2682cb019bc1a.tar.gz cpython-93930eaf0acd64dc0d08d58321d2682cb019bc1a.tar.bz2 |
gh-111139: Optimize math.gcd(int, int) (#113887)
Add a fast-path for the common case.
Benchmark:
python -m pyperf timeit \
-s 'import math; gcd=math.gcd; x=2*3; y=3*5' \
'gcd(x,y)'
Result: 1.07x faster (-3.4 ns)
Mean +- std dev: 52.6 ns +- 4.0 ns -> 49.2 ns +- 0.4 ns: 1.07x faster
Diffstat (limited to 'Modules/mathmodule.c')
-rw-r--r-- | Modules/mathmodule.c | 14 |
1 files changed, 9 insertions, 5 deletions
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c index 6cd61e9..2a796c1 100644 --- a/Modules/mathmodule.c +++ b/Modules/mathmodule.c @@ -759,13 +759,17 @@ m_log10(double x) static PyObject * math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs) { - PyObject *res, *x; - Py_ssize_t i; + // Fast-path for the common case: gcd(int, int) + if (nargs == 2 && PyLong_CheckExact(args[0]) && PyLong_CheckExact(args[1])) + { + return _PyLong_GCD(args[0], args[1]); + } if (nargs == 0) { return PyLong_FromLong(0); } - res = PyNumber_Index(args[0]); + + PyObject *res = PyNumber_Index(args[0]); if (res == NULL) { return NULL; } @@ -775,8 +779,8 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs) } PyObject *one = _PyLong_GetOne(); // borrowed ref - for (i = 1; i < nargs; i++) { - x = _PyNumber_Index(args[i]); + for (Py_ssize_t i = 1; i < nargs; i++) { + PyObject *x = _PyNumber_Index(args[i]); if (x == NULL) { Py_DECREF(res); return NULL; |