In this blog post I will give a simple example of using the section member function for array and array_view, demonstrating how to offset your origin point in order to operate on a smaller section of data in your computation. So for example if your data is matrix that looks like this:
array_view<float, 2> qin(height, width, data);
Where height and width are divisible by 2, you can view it in four quarters as follows:
array_view<float, 2> q1 = qin.section(index<2>(0, 0), extent<2>(height/2, width/2));
array_view<float, 2> q2 = qin.section(index<2>(height/2,0), extent<2>(height/2, width/2));
array_view<float, 2> q3 = qin.section(index<2>(0,width/2), extent<2>(height/2, width/2));
array_view<float, 2> q4 = qin.section(index<2>(height/2, width/2));
Below is a complete code example that does a summation of all elements in the array_view ‘qin’ and places the result in the first element. The algorithm views the data as two dimensions and splits it into four quarters, and then it sums up all elements in one quarter ‘qout’. By repeating this operation making ‘qout’ to be ‘qin’ it stores the overall reduction result in qin(0,0).
The code demonstrates the section functionality, but is not aimed to be (and indeed isn’t) an optimum implementation of a reduction algorithm (we have one of those in the pipeline) – it was written simply to demonstrate usage of the section API.
Also notice that ‘q1’ creation - line(35) - can benefit from the section overloads to retrieve same view as follows:
array_view<float,2> q1 = qin.section(quarterdim);
In this case the extent is inferred to cover the rest of the parent array/array_view.
array_view<float,2> q1 = qin.section(0, 0, height, width);
Similarly q2 and q3 can be created using the latter section function call.
Finally, one might look close to ‘q1’ and ask couldn’t ‘qin’ replace its functionality and reduce the number of lines of code? The answer is “yes”, but that would introduce a performance overhead; instead of copying 4 quarters to GPU memory, this change will copy 3 quarters plus the whole matrix. Also copying data back to the host would again copy the whole matrix instead of just one quarter of it.
That completes my example for creating sub-sections using the section member function. Feel free to ask questions in the comments section below or in our MSDN forum.