Search code examples
iofortran

Optimal way to write 2d array into unformatted file using nested implicit loops


I have a piece of code writing a 2D array var into a fortran unformatted file. I'd prefer it to be written line-by-line. I therefore need to loop in an non-optimal order fortran-wise, because it is recommended to loop on the outer dimension first.

write(fileid, pos = pos) ((var(i,j),j=1,size(var,2)),i=1,size(var,1))

I'm wondering whether transposing the way I write into the file would be more optimal, or whether this is not necessary because the I/O process should be dominating over the cache/memory access in this situation.


Solution

  • I am a retired Fortran compiler and I/O library developer, and my experience here is that you would be far better off to write the whole array. Using implied loops as you have it, out of memory order, will typically require each element to be transmitted separately to the I/O library, with lots of processing overhead per element. Writing the whole array can result in a single I/O transfer directly from your array.

    Given that you are using unformatted I/O, I don't understand the desire to write a row at a time, unless this is going to be read by some other software.