Skip to content

Commit

Permalink
pythongh-111139: Optimize math.gcd(int, int)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
vstinner committed Jan 10, 2024
1 parent beb80d1 commit 4836334
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 4836334

Please sign in to comment.