Skip to content

Avoid a temporary float in PyFloat_AsDouble() for exact ints #162477

Description

@maurycy

Feature or enhancement

When a caller such as math.sqrt(42) asks for a C double, PyFloat_AsDouble() calls the integer's nb_float slot. That slot calls PyLong_AsDouble() and wraps the result in a Python float. The caller then reads the same double and releases the temporary float.

cpython/Objects/longobject.c

Lines 5974 to 5981 in 22691a3

long_float(PyObject *v)
{
double result;
result = PyLong_AsDouble(v);
if (result == -1.0 && PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(result);
}

For an exact int, PyFloat_AsDouble() could return PyLong_AsDouble() directly...

macOS M4 PGO+LTO:

Operation Baseline Patched Baseline / patched
sqrt(42) 16.40 ns 13.06 ns 1.256x
pack(1, 2, 3) 40.08 ns 30.64 ns 1.308x
array('d', ints) 10.31 µs 7.19 µs 1.433x
array('d', floats) (control) 6.65 µs 6.16 µs 1.080x

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. added
    type-feature
    on Nov 23, 2026
  2. added
    interpreter-core
    performance
    on Nov 23, 2026
  3. sergey-miryanov commented on Nov 23, 2026

    @sergey-miryanov
    Contributor

    How will this change affect performance benchmarks?

  4. added a commit that references this issue on Nov 23, 2026
  5. vstinner commented on Nov 23, 2026

    @vstinner
    Member

    How will this change affect performance benchmarks?

    I don't expect significant impact on pyperformance macro benchmarks. But IMO it's still worth it since it's faster on micro benchmarks.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coreperformancetype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions