加快阅读和打开文件

Speed up reading and opening files

我正在尝试循环读取多个文件,但似乎我的代码每次都读取文件,这使得它变慢了。我已经包含了一个标志,用于仅在第一次读取文件时使用,但它似乎不起作用。如何使代码更快?

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

我的 fortran 已经生锈了,但我认为它应该看起来像:

    if(first_time) then
           OPEN(99,FILE=FN, action='read', status='old', position='rewind')                                     
           do inner_row=1,max_rows
               read (99,*) (inner_coord(inner_row,l),l=1,3)!coorda, coordb, coordc
               coord(:,9*I+3*j+k-12)=inner_coord(:,3)
               CLOSE(99)  
           enddo
          first_time=.false.
    enddo

我可能是错的,但在我看来你正在以低效的方式进行循环。您打开文件并逐行移动到文件读取的末尾,并且仅使用上次读取(1448 次,太多)。相反,我会摆脱外部循环(带行索引)并将 coord(:,9*I+3*j+k-12)=inner_coord(:,3) 移到上面的循环内并放在 read .