I'm trying to read in multiple files in a loop but it appears my code reads the files each time which makes it slow. I have included a flag to read the files the first time only but it doesn't seem to work. How do I make the code faster?
program readfiles
use variables
use trilinear
implicit none
real:: coord(1448,27), inner_coord(1448,3), interpolated_array(1448) !
integer :: i, j, N, zeta, lam, k, l, m, row, inner_row, max_rows
Logical :: first_time = .True.
CHARACTER(len=100) :: FN
type(string) :: array(3)
N=3 !--arbitrary number of files
array(1)%str = '2e8'
array(2)%str = '2e9'
array(3)%str = '3e9'
if(first_time) then
max_rows=1448
do row=1, max_rows
lam = 80
DO I=1,N
lam = lam + 60
zeta=20
do j=1,N
zeta = zeta + 20
do k=1,N
WRITE(FN,10)lam, zeta, (array(k)%str)!,k=1,N)
OPEN(99,FILE=FN, action='read', status='old', position='rewind')!open the file to read
do inner_row=1,max_rows
read (99,*) (inner_coord(inner_row,l),l=1,3)!coorda, coordb, coordc
enddo
coord(:,9*I+3*j+k-12)=inner_coord(:,3)
CLOSE(99) !this ensures it closes d file it is reading from so a new one can b opened for reading
enddo
enddo
END DO
ENDDO
10 FORMAT('4e3_2048_',(I3.0),'_',(I2.2),'_',(A3),'.ksz_cl.txt') !length of this is decided by FN
first_time = .False.
endif
print *, first_time
interpolated_array = trilinear_mod(150.0,70.0,2000000000.0,coord)
open (unit=96, file='interpolated_array.txt') !This bit flattens the array
do m = 1,max_rows
write(96,'(30f16.13)') interpolated_array(m) !'(27f13.10)'
enddo
end program readfiles
I could be wrong but seems to me that you are doing your loop in inefficient way. You open file and move to the end of the file reading line by line and only use last read (1448 times, too much). Instead I would rid off outer loop (with row index) and move coord(:,9*I+3*j+k-12)=inner_coord(:,3) inside of the loop above and put under read.