Search code examples
fortrangfortranintel-fortranfortran95

How to implement Structures of Arrays instead of Arrays of Structures in Fortran?


I'm writing my code on CFD topic with Fortran. After discussing with some friends from computer science, they told me that one could speed up the computation time if one implements Structures of Arrays (SoA) instead of Arrays of Structures (AoS) on his/her code.

There are many examples I've seen about this topic's implementation, but most of them are in C or C++. (e.g. https://software.intel.com/en-us/articles/how-to-manipulate-data-structure-to-optimize-memory-use-on-32-bit-intel-architecture).

Could anyone show me or guide me some basic ideas or examples how to implement SoA instead of AoS in Fortran?


Solution

  • There is really nothing difficult about this concept.

    Instead of

    type struct
      real x, y, z
    end type
    
    type(struct), allocatable :: array(:)
    

    you use

    type(struct2)
      real, dimension(:), allocatable :: x, y, z
    end ype
    
    type(struct2) :: arrays
    

    It is really just a line by line translation of a C or C++ example. More or less everything what you can read about this topic is still applicable to Fortran even if they use other language for their examples.

    Actually, in the old days Fortran didn't have any structures and the most natural way how to do stuff was just to declare variables:

    real x(bigN)
    real y(bigN)
    real z(bigN)
    

    and you get all those performance benefits of structures of arrays this way too. It sounds almost strange to a Fortranner that someone knows only arrays of structures.