On 04/17/2017 02:49 PM, eryk sun wrote:
On Mon, Apr 17, 2017 at 5:58 PM, Rob Gaddi
<rgaddi@highlandtechnology.invalid> wrote:
buffertype = c_uint8 * size
return addressof(buffertype.from_buffer(buf, offset))

works but is inefficient and woefully inelegant.

A lot of the cost there is in creating buffertype, but why do you need
that? You can use c_char.from_buffer if all you need is the base
address.

    import ctypes

    def addressof_buffer(buf):
        return ctypes.addressof(ctypes.c_char.from_buffer(buf))

    >>> b = bytearray(b'spam')
    >>> addressof_buffer(b)
    2619159025048
    >>> ctypes.string_at(2619159025048, 5)
    b'spam\x00'


That's a good catch, that takes some of the stupider part out. Performance is still 5x slower, but if I'm really groveling for 200ns then I'm either using the wrong language or doing the wrong thing.

In [12]: from ctypes import *
In [13]: ba = bytearray(1024)
In [14]: cta = create_string_buffer(1024)

In [15]: %timeit(c_uint8.from_buffer(ba))
1000000 loops, best of 3: 252 ns per loop

In [16]: %timeit addressof(c_uint8.from_buffer(ba))
1000000 loops, best of 3: 284 ns per loop

In [17]: %timeit addressof(cta)
10000000 loops, best of 3: 52 ns per loop

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to