robertwb / issues-import-test

0 stars 0 forks source link

Inefficient unpacking of std::pair #108

Open robertwb opened 7 years ago

robertwb commented 7 years ago

Reported by Pastafarianist on 28 Nov 2015 19:42 UTC '''test.py:'''

import pyximport
pyximport.install()

import module

'''module.pyx:'''

from libcpp.map cimport map
from libcpp.utility cimport pair
from libc.stdint cimport uint32_t

cdef main():
    cdef map[uint32_t](uint32_t,) m
    cdef pair[uint32_t](uint32_t,) mypair
    m[= 2

    for key, value in m:
        print(key, value)

    for item in m:
        key, value = item
        print(key, value)

    for item in m:
        key, value = item.first, item.second
        print(key, value)

    for mypair in m:
        key, value = mypair
        print(key, value)

main()

'''module.pyxbld:'''

def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(
        name=modname,
        sources=[pyxfilename](1]),
        language='c++'
    )

In the example above, Cython only produces efficient code in the third for loop by directly reading from pair.first and pair.second. The other examples result in C++ code that first calls __pyx_convert_pair_to_py_uint32_t____uint32_t and then does a lot of checks to ensure that what was returned is a 2-element tuple.

As far as I understand, Cython already knows that item is a pair. Is it possible to optimize away these checks?

Migrated-From: http://trac.cython.org/ticket/875