Skip to content
This repository has been archived by the owner on Sep 27, 2021. It is now read-only.

Commit

Permalink
Use opportunistic zero-copy strategy in send (#35)
Browse files Browse the repository at this point in the history
Use `ffi.from_buffer` more aggressively when the data type and CFFI version
support it.  Older versions of CFFI don't support commonly used types
like `bytes` but do work for some variants of `memoryview`.  Instead of
instance and version checking all the permutations this patch attempts the
fast path first and catches `TypeError` as a condition to degrade to the slow
path of `ffi.new`.

See: http://cffi.readthedocs.io/en/latest/ref.html#ffi-buffer-ffi-from-buffer

Fixes #34
  • Loading branch information
mayfield authored and djc committed Sep 20, 2016
1 parent 9542b55 commit 5269d26
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions nnpy/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,13 @@ def connect(self, addr):
return errors.convert(rc, rc)

def send(self, data, flags=0):
if isinstance(data, memoryview):
# Some data types can use a zero-copy buffer creation strategy when
# paired with new versions of CFFI. Namely, CFFI 1.8 supports `bytes`
# types with `from_buffer`, which is about 18% faster. We try the fast
# way first and degrade as needed for the platform.
try:
buf = ffi.from_buffer(data)
else:
except TypeError:
data = data.encode() if isinstance(data, ustr) else data
buf = ffi.new('char[%i]' % len(data), data)
rc = nanomsg.nn_send(self.sock, buf, len(data), flags)
Expand Down

0 comments on commit 5269d26

Please sign in to comment.