Created
January 9, 2020 15:48
-
-
Save hgomersall/a24b7af65ad3cdb54bbf20fc88ab9deb to your computer and use it in GitHub Desktop.
Simple pure python function to return an empty n-byte-aligned array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def empty_aligned(shape, dtype='float64', order='C', n=None): | |
'''empty_aligned(shape, dtype='float64', order='C', n=None) | |
Function that returns an empty numpy array that is n-byte aligned, | |
where ``n`` is determined by inspecting the CPU if it is not | |
provided. | |
The alignment is given by the final optional argument, ``n``. If ``n`` is | |
not set then the default alignment is used. | |
The rest of the arguments are as per :func:`numpy.empty`. | |
''' | |
if n is None: | |
n = 1 | |
itemsize = np.dtype(dtype).itemsize | |
# Apparently there is an issue with numpy.prod wrapping around on 32-bits | |
# on Windows 64-bit. This shouldn't happen, but the following code | |
# alleviates the problem. | |
if not isinstance(shape, (int, np.integer)): | |
array_length = 1 | |
for each_dimension in shape: | |
array_length *= each_dimension | |
else: | |
array_length = shape | |
# Allocate a new array that will contain the aligned data | |
_array_aligned = np.empty(array_length*itemsize+n, dtype='int8') | |
# We now need to know how to offset _array_aligned | |
# so it is correctly aligned | |
_array_aligned_offset = (n - _array_aligned.ctypes.data)%n | |
array = np.frombuffer( | |
_array_aligned[_array_aligned_offset:_array_aligned_offset-n].data, | |
dtype=dtype).reshape(shape, order=order) | |
return array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment