Skip to content

Commit 208798e

Browse files
committed
pythongh-111139: Optimize math.gcd(int, int)
Add a fast-path for the common case.
1 parent beb80d1 commit 208798e

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

Modules/mathmodule.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,16 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
765765
if (nargs == 0) {
766766
return PyLong_FromLong(0);
767767
}
768+
769+
// Fast-path for the common case: avoid calling _PyNumber_Index()
770+
// and the loop.
771+
if (nargs == 2
772+
&& PyLong_CheckExact(args[0])
773+
&& PyLong_CheckExact(args[1]))
774+
{
775+
return _PyLong_GCD(args[0], args[1]);
776+
}
777+
768778
res = PyNumber_Index(args[0]);
769779
if (res == NULL) {
770780
return NULL;

0 commit comments

Comments
 (0)