Buffers and pointers (Py3.4)
rgaddi at highlandtechnology.invalid
Mon Apr 17 21:29:50 EDT 2017
On 04/17/2017 02:49 PM, eryk sun wrote:
> On Mon, Apr 17, 2017 at 5:58 PM, Rob Gaddi
> <rgaddi at 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
> import ctypes
> def addressof_buffer(buf):
> return ctypes.addressof(ctypes.c_char.from_buffer(buf))
> >>> b = bytearray(b'spam')
> >>> addressof_buffer(b)
> >>> ctypes.string_at(2619159025048, 5)
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 : from ctypes import *
In : ba = bytearray(1024)
In : cta = create_string_buffer(1024)
In : %timeit(c_uint8.from_buffer(ba))
1000000 loops, best of 3: 252 ns per loop
In : %timeit addressof(c_uint8.from_buffer(ba))
1000000 loops, best of 3: 284 ns per loop
In : %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.
More information about the Python-list