1 | """ |
---|
2 | GPU data alignment. |
---|
3 | |
---|
4 | Some web sites say that maximizing performance for OpenCL code requires |
---|
5 | aligning data on certain memory boundaries. The following functions |
---|
6 | provide this service: |
---|
7 | |
---|
8 | :func:`align_data` aligns an existing array, returning a new array of the |
---|
9 | correct alignment. |
---|
10 | |
---|
11 | :func:`align_empty` to create an empty array of the correct alignment. |
---|
12 | |
---|
13 | Set alignment to :func:`gpu.environment()` attribute *boundary*. |
---|
14 | |
---|
15 | Note: This code is unused. So far, tests have not demonstrated any |
---|
16 | improvement from forcing correct alignment. The tests should |
---|
17 | be repeated with arrays forced away from the target boundaries |
---|
18 | to decide whether it is really required. |
---|
19 | """ |
---|
20 | import numpy as np # type: ignore |
---|
21 | |
---|
22 | def align_empty(shape, dtype, alignment=128): |
---|
23 | """ |
---|
24 | Return an empty array aligned on the alignment boundary. |
---|
25 | """ |
---|
26 | size = np.prod(shape) |
---|
27 | dtype = np.dtype(dtype) |
---|
28 | # allocate array with extra space for alignment |
---|
29 | extra = alignment//dtype.itemsize - 1 |
---|
30 | result = np.empty(size+extra, dtype) |
---|
31 | # build a view into allocated array which starts on a boundary |
---|
32 | offset = (result.ctypes.data%alignment)//dtype.itemsize |
---|
33 | view = np.reshape(result[offset:offset+size], shape) |
---|
34 | return view |
---|
35 | |
---|
36 | def align_data(x, dtype, alignment=128): |
---|
37 | """ |
---|
38 | Return a copy of an array on the alignment boundary. |
---|
39 | """ |
---|
40 | # if x is contiguous, aligned, and of the correct type then just return x |
---|
41 | view = align_empty(x.shape, dtype, alignment=alignment) |
---|
42 | view[:] = x |
---|
43 | return view |
---|