It is getting even more interesting. I have checked the number of times the address of the allocated array really changes after ‘reallocation’. The result was very surprising. It seems that the address changes are extremely rare. When the
allocated array is shrinking, almost no changes happen. Which would be obvious but from the timing, it seems that the data gets copied on every operation both ways.
BTW, is there a standard-conforming way of getting the address of a variable, other than LOC(variable)
extension?
gfortran-10 -O3 realloc.f90
./a.out 100000
up: 35 addr changes 2.97556090 secs
down: 2 addr changes 1.71359110 secs
./a.out 200000
up: 38 addr changes 12.1577778 secs
down: 2 addr changes 7.31757259 secs
program testrealloc
real, allocatable :: a(:)
real :: t0, t1
integer(kind=8) :: p1, p2
integer :: i, nch=0, max=10000
character(len=16) :: arg
if ( command_argument_count() .ge. 1 ) then
call get_command_argument(1, arg)
read(arg,*) max
endif
allocate(a(1))
p1 = loc(a)
call cpu_time(t0)
do i=2, max
a = [ a, real(i) ]
p2 = loc(a)
if ( p2 /= p1 ) nch=nch+1
p1 = p2
end do
call cpu_time(t1)
print *, 'up: ', nch, 'addr changes', t1-t0, ' secs'
nch = 0
call cpu_time(t0)
do i=max-1, 1, -1
a = a(1:i)
p2 = loc(a)
if ( p2 /= p1 ) nch=nch+1
p1 = p2
end do
call cpu_time(t1)
print *, 'down:', nch, 'addr changes', t1-t0, ' secs'
end program testrealloc