Skip to content

PyType_GetModuleByDef family for binary functions performance #117578

Description

@neonene

Feature or enhancement

Proposal:

When implementing an extension module with a module state enabled,
binary tp slot functions (e.g. nb_add) need two PyType_GetModuleByDef() to be used like the following to compare the given types with a heap-type object in the module state, which can be slow:

static PyObject *
foo_add(PyObject *left, PyObject *right)
{
    ...
    PyObject *module = PyType_GetModuleByDef(Py_TYPE(left), &module_def);
    if (module == NULL) {
        PyErr_Clear();
        module = PyType_GetModuleByDef(Py_TYPE(right), &module_def);
    }
    ...
}
  • 3.13.0 alpha5 _decimal (module state ver.)
from timeit import timeit
f = lambda s: timeit(s, 'import _decimal; d = _decimal.Decimal(1)')
a = f('d + 1')
b = f('1 + d')
print('d + 1:', a)
print('1 + d:', b,  b / a)
d + 1: 0.11202071857405826
1 + d: 0.49533294743326095 4.421797625818569

The difference mainly comes from a TypeError emission from PyType_GetModuleByDef(), so it would be nice if we could have a new function which receives two types and emits an error after checking them.

cc @encukou

Related issue:

Linked PRs

Activity

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions