Extended time measurement with CPU_TIME() in fortran with loops located after the last call?

91 Views Asked by At

I am trying to measure the time of a given loop with the cpu_time function. The piece of code I am currently testing is as follows. t_start and t_finish are two reals.

    call cpu_time(t_start)
    
    do ii = 1, 1000000
        
        ** do something that produces an integer named set_count **
        
        ! --- Result is stored in an array of integers named buffer
        buffer(ii) = set_count
    
    end do
    
    call cpu_time(t_finish)

    write(*,'(A,F12.6,A)')'Elapsed CPU time = ',(t_finish-t_start),' seconds.'
   
    !do ii = 0, Ns
    !    sethands(ii) = sethands(ii) + count((buffer == ii))
    !end do

When compiled with GNU Fortran 13.2.0 (with the command gfortran -O3 <file_in> -o <file_out>), and executed in Mysys Mingw64 environment in Windows 10, the code gives the following console output:

Elapsed CPU time =     1.531250 seconds.

Now I uncomment the small block which is placed after the last call of the cpu_time function. In this loop, sethands is an array of integers:

    do ii = 0, Ns
        sethands(ii) = sethands(ii) + count((buffer == ii))
    end do

The execution time is much longer, and I obtain the following result:

Elapsed CPU time =   127.109375 seconds.

The result looks very surprising to me. Why do I have a different result? And why such a large discrepancy? If the last loop is time consuming, why is t_finish-t_start affected, as it is supposed to be calculated before entering in the last loop?

How to improve the storage of the buffer data in the last loop, so as to avoid such a large lead time?

Pardon me if this question is a duplication of a similar thread.

1

There are 1 best solutions below

0
PierU On

Regarding your last question, the following code will be likely more efficient:

do i = 1, size(buffer)
   ii = buffer(i)
   if (ii >= 0 .and. ii <= Ns) sethands(ii) = sethands(ii) + 1
end do

You don't even need the test if you know that it will always evaluate to .true.