Skip to content

gh-162477: Use PyLong_AsDouble() for exact ints in PyFloat_AsDouble() - #162478

Merged
StanFromIreland merged 5 commits into
python:mainfrom
maurycy:pyfloat-asdouble-int
Nov 23, 2026
Merged

StanFromIreland merged 5 commits into
python:mainfrom
maurycy:pyfloat-asdouble-int

Conversation

@maurycy

@maurycy maurycy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Call PyLong_AsDouble() directly for exact int arguments.

PGO+LTO macOS M4:

Operation Baseline Patched Baseline / patched
sqrt(42) 16.40 ns 13.06 ns 1.256×
pack(1, 2, 3) 40.08 ns 30.64 ns 1.308×
array('d', ints) 10.31 µs 7.19 µs 1.433×
array('d', floats) (control) 6.65 µs 6.16 µs 1.080×
pyperf bench
from array import array
from math import sqrt
from struct import Struct

import pyperf


ints = list(range(1, 1001))
floats = list(map(float, ints))
large_int = 2**200
pack = Struct("!ddd").pack

runner = pyperf.Runner()
for stmt in (
    "sqrt(42)",
    "sqrt(42.0)",
    "sqrt(large_int)",
    "sum(map(sqrt, ints))",
    "sum(map(sqrt, floats))",
    "pack(1, 2, 3)",
    "pack(1.0, 2.0, 3.0)",
    "array('d', ints)",
    "array('d', floats)",
):
    runner.timeit(stmt, stmt, globals=globals())

Closes #162477

@eendebakpt

Copy link
Copy Markdown
Contributor

The change itself looks ok. How important is the int case for PyFloat_AsDouble? The float case will probably not suffer as the fast check with PyFloat_Check is before the new fast path.

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. I think that it's worth it to make this small optimization: it's 1.08x to 1.43x faster on the micro benchmarks.

Comment thread Objects/floatobject.c Resolved
Co-authored-by: Victor Stinner <vstinner@python.org>
@vstinner

Copy link
Copy Markdown
Member

The float case will probably not suffer as the fast check with PyFloat_Check is before the new fast path.

Yeah, (exact) float input should be the common case and it's not affected by this change.

@StanFromIreland
StanFromIreland merged commit f9e53a5 into python:main Nov 23, 2026
57 checks passed
@StanFromIreland

Copy link
Copy Markdown
Member

Merged, thanks.

@maurycy
maurycy deleted the pyfloat-asdouble-int branch November 23, 2026 20:05
@maurycy

maurycy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@StanFromIreland Thank you for merging:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Avoid a temporary float in PyFloat_AsDouble() for exact ints

4 participants