Skip to content

[PERF]: Improve conversion of Python sequences to C++ vectors #1644

Closed

Description

@mdboom

Conversion of Python sequences to C++ vectors currently looks like:

cdef vector[cydriver.CUatomicOperation] cyoperations = [int(pyoperations) for pyoperations in (operations)]

This has a number of suboptimal things:

  • It creates a temporary Python list (which may be realloc'd multiple times as it grows) that is totally unnecessary.
  • List comprehensions are significantly slower than for loops in Cython, since the former requires making multiple Python-level calls to an iterator object.

Instead, we know the length of the sequence in advance, so we can resize or pre-allocate the vector of the correct size, and then fill it with a for loop.

Activity

  1. added this to the cuda.bindings 13.2 milestone on Feb 18, 2026
  2. mdboom commented on Feb 19, 2026

    @mdboom
    ContributorAuthor

    An example as to where this pattern is used is in cuModuleLoadDataEx. However, even with a sequence of ~100 elements, I can't seem to get this change to move the needle. So closing as ineffective.

  3. jakirkham commented on Feb 20, 2026

    @jakirkham

    TBH it is possible that the most succinct form is also the most efficient form

    cdef vector[cydriver.CUatomicOperation] cyoperations = operations

    At least looking at a similar case

    cdef vector[Py_ssize_t] cy_range_to_vector(Py_ssize_t N):
        cdef vector[Py_ssize_t] L = range(N)
        return L

    Cython generates code from this template, which does what you describe above

  4. mdboom commented on Feb 20, 2026

    @mdboom
    ContributorAuthor

    Thanks for that @jakirkham. With your suggestion, I can shave off 100ns. Not nothing, especially since it actually simplifies our code.

  5. reopened this on Feb 20, 2026
  6. added a commit that references this issue on Feb 20, 2026
    f66c340
  7. added a commit that references this issue on Feb 20, 2026
    4597e03
  8. jakirkham commented on Feb 20, 2026

    @jakirkham

    Happy to help 🙂

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions