Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 93930ea

Browse filesBrowse files
authored
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
1 parent 66363b9 commit 93930ea
Copy full SHA for 93930ea

File tree

Expand file treeCollapse file tree

1 file changed

+9
-5
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+9
-5
lines changed

‎Modules/mathmodule.c

Copy file name to clipboardExpand all lines: Modules/mathmodule.c
+9-5Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -759,13 +759,17 @@ m_log10(double x)
759759
static PyObject *
760760
math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
761761
{
762-
PyObject *res, *x;
763-
Py_ssize_t i;
762+
// Fast-path for the common case: gcd(int, int)
763+
if (nargs == 2 && PyLong_CheckExact(args[0]) && PyLong_CheckExact(args[1]))
764+
{
765+
return _PyLong_GCD(args[0], args[1]);
766+
}
764767

765768
if (nargs == 0) {
766769
return PyLong_FromLong(0);
767770
}
768-
res = PyNumber_Index(args[0]);
771+
772+
PyObject *res = PyNumber_Index(args[0]);
769773
if (res == NULL) {
770774
return NULL;
771775
}
@@ -775,8 +779,8 @@ math_gcd(PyObject *module, PyObject * const *args, Py_ssize_t nargs)
775779
}
776780

777781
PyObject *one = _PyLong_GetOne(); // borrowed ref
778-
for (i = 1; i < nargs; i++) {
779-
x = _PyNumber_Index(args[i]);
782+
for (Py_ssize_t i = 1; i < nargs; i++) {
783+
PyObject *x = _PyNumber_Index(args[i]);
780784
if (x == NULL) {
781785
Py_DECREF(res);
782786
return NULL;

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.