Search code examples
pointersfortranfortran2008

Performance of a non-contiguous pointer array pointing to a one dimensional target array in fortran


I have a code in which a one-dimensional array R is used which has 3N elements. You can think of it as the position vector of N particles, such that R=[r1x,r1y,r1z,r2x,r2y,...]. Note that the pattern should be defined as this for concise usage of the array.

In sections of the code, I need to perform some operations only on the x-coordinates. I am currently using something like this:

Rx => R(1:3N-2:3)

and Rx is subsequently used in the operations. This makes the access non-contiguous but I was wondering if I can hope for a way to vectorize the operations. Alternatively, one may use OMP with a loop over the particles. I want to get the expert's idea on this matter and particularly the best possible practice performance-wise.


Solution

  • You can't have your cake and eat it too. If you want to make strided access to non-contiguous array elements you're going to pay a price in performance. For small arrays, in which all the elements fit into cache, you'll probably never notice the price. For larger arrays you'll do a lot more data movement through cache than if you step through array elements one-by-one in memory-layout order. Using pointers to non-contiguous array sections doesn't magically alter these facts (as you seem to be aware).

    So what you do is what Fortran programmers have always done, optimise the memory layout of your arrays for the most common access pattern. In your case many of us would have either a 3,x rank-2 array or a x,3 one depending on whether accessing all the x (or y or z) elements together was more frequent than accessing particle-by-particle.

    Sometimes it's worth transposing an array prior to operations on elements in non-memory-layout order. Sometimes it's even worth holding the same data twice, once in one order, once in the other. But you're going to have to figure out which is the best solution for your program, we don't have all the facts necessary to provide a high-quality recommendation. If it matters to you, then it should matter enough for you to conduct some tests and develop a quantified view of the situation.

    You pays your money and you makes your choice.