【问题标题】:Speed up reading and opening files加快阅读和打开文件的速度
【发布时间】:2019-09-09 09:07:42
【问题描述】:

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

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

【问题讨论】:

  • first_time 上的测试在您程序中的所有循环之外。这可能不是你想要的。

标签: fortran gfortran


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我的 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
    

    【讨论】:

    • 我认为没有必要检查first_time。文件将打开一次,因为组合 lam,zeta,array(k)%str (假设 array(k)%str 对于给定的 k 值是唯一的)是唯一的。 Close(99) 必须在 inner_row 循环之外。根本不需要 first_time 变量。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 2022-08-05
    • 1970-01-01
    相关资源
    最近更新 更多