而不是使用三个连续的标量IF语句我想使用带有向量参数的单个IF语句(如果可能的话)。我无法弄清楚如何。是否有可能在Fortran IF语句中使用向量参数而不是标量参数
想要这个的原因是测试它的速度。我的代码可以在几天内运行数天。即使稍微加快速度也可以产生很大的差异。
下面是虚拟场景中带有三条IF语句的工作代码。
program main
!==============================================
! Define variables
!==============================================
real, dimension(10,3) :: r ! 10 atoms each with x,y,z coordinates
real, dimension(3) :: rij ! x,y,z vector of difference between two atoms
real :: Box_Length ! length of simulation box
real :: time, timer_start, timer_end
integer :: timer
!=======================================================
! Begin Program body
!=======================================================
Box_Length = 1.0 ! based on a box of length = 1 since coords are randomly generated between 0 and 1
!=================================
! Generate random atom coordinates
!=================================
r = 0.0
CALL RANDOM_NUMBER (r)
!=================================
! Begin algorithm
!=================================
call cpu_time(timer_start)
do timer = 1,30000
do i = 1,size(r)
do j = 1, size(r)
if(i == j) cycle
rij(:) = abs(r(i,:) - r(j,:))
!==============================
! Apply mirror image convention
!==============================
if(rij(1) > Box_Length - rij(1)) rij(1) = rij(1) - Box_Length
if(rij(2) > Box_Length - rij(2)) rij(2) = rij(2) - Box_Length
if(rij(3) > Box_Length - rij(3)) rij(3) = rij(3) - Box_Length
!*******************************************************************************
! Question: Can I make it into a single if statement i.e. *
! *
! if(rij(:) > Box_Length(:) - rij(:)) rij(:) = rij(:) - Box_Length(:) *
! *
! Where Box_Length is now a vector and only the coordinate that triggers *
! the if statement is modified. Meaning that if { rij(2) > Box_Length - rij(2) } *
! only rij(2) is modified, not all three. *
! I have tried making Box_Length a vector, but that failed. *
!*******************************************************************************
! insert rest of algorithm
enddo ! j-loop
enddo ! i loop
enddo ! timer loop
call cpu_time(timer_end)
time = timer_end - timer_start
print*, 'Time taken was: ', time
end program main
感谢您的任何帮助把它变成一个向量化的IF语句。另外,我在列和行向量之间来回翻转。目前列向量对我来说工作得更快。这不是关于列向量与行向量的问题。我按自己的时间安排,并使用更快的方法。我根本无法获得工作矢量方法来尝试计时。
if语句等同于'rij = min(rij,Box_length-rij)'。我想这只是一个测试用例,在实际的代码版本中,size(r)而不是size(r,dim = 1)的使用是正确的。因为它有一个界限错误,并且正在做额外的工作。你可能能够利用对称性并避免看起来像'j> i'的50%冗余工作,但这是另一个问题。 – RussF
你是对的,在我的真实代码中,事情更加简化。我喜欢'rij = min(rij,Box_length-rij)'的想法。我试了一下,在这个虚拟例子中比三个IF或WHERE稍慢。但是,在我的主要代码中,它似乎稍快。分子模拟中常用的方法是'rij = rij-Box_Length * ANINT(rij/BoxSize)',这种方法非常慢。它是使用三个IF语句的一半速度。 –