pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://github.com/python/cpython/commit/93930eaf0acd64dc0d08d58321d2682cb019bc1a

b55097560d244c08.css" /> gh-111139: Optimize math.gcd(int, int) (#113887) · python/cpython@93930ea · GitHub
Skip to content

Commit 93930ea

Browse 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

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

Modules/mathmodule.c

Lines 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)
pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy