From 4836334d195462cff82ee31bd51829a679a4f7a5 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Wed, 10 Jan 2024 02:01:07 +0100 Subject: [PATCH] gh-111139: Optimize math.gcd(int, int) 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 --- Modules/mathmodule.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c index 6cd61e9ab75424e..6edc5a56552c4de 100644 --- a/Modules/mathmodule.c +++ b/Modules/mathmodule.c @@ -765,6 +765,16 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs) if (nargs == 0) { return PyLong_FromLong(0); } + + // Fast-path for the common case: avoid calling _PyNumber_Index() + // and the loop. + if (nargs == 2 + && PyLong_CheckExact(args[0]) + && PyLong_CheckExact(args[1])) + { + return _PyLong_GCD(args[0], args[1]); + } + res = PyNumber_Index(args[0]); if (res == NULL) { return NULL;