-4

The following Fortran function takes forever to print the Hello World 2 after printing Hello World 1.

program Test_Long_Run

    implicit none

    ! Variables

    integer,allocatable,dimension(:) :: test
    integer :: i, j, k, l, m, int
    
    allocate(test(1000*100)); test = 0
    ! Body of Test_Long_Run
    print *, 'Hello World 1'
    do k = 1,100
        do j = 1,100
            do i = 1,100
                do m = 1,100
                    do l = 1,1000
                        test(l*m) = 2
                        int = 2
                    enddo
                enddo
            enddo
        enddo
    enddo
    
    print *, 'Hello World 2'

end program Test_Long_Run

It runs very fast if I comment out test(l*m) = 2

Safdar
  • 1
  • 5
    You're running a loop involving an assignment and a multiplication a 100 billion times and you're asking why the loop is faster when you remove the assignment and multiplication? Are you just trolling here? Doing something a 100 billion times is a lot slower than not doing it at all. – Grismar Jan 04 '21 at 22:59
  • After removing the calculation and assignment the only thing left in the loop is the assignment of a constant to a variable. It seems likely this would be removed from the loop by an optimization run during compilation. – massfords Jan 05 '21 at 04:23
  • You did no even tell use how you compiled the code. How can you wonder it is not optimized out if you do not tell use your exact compiler flags? – Vladimir F Героям слава Jan 05 '21 at 09:12

1 Answers1

2

The instructions in the inner body perform 100 billion multiplication and assignments to a table, plus an assignment to a variable. The array you write to contains 100 thousand integers, so does not fit into any cache. The elements you write to are not contiguous (stride: 1000*4 bytes), so each write must bypass/invalidate the cache and involve RAM. This is slow. Even hundreds of processor cycles per each assignment. If your processor runs at 2GHz, or at 2 billion instructions per second, you will make at most 10 million assignments per second. Now divide 100 billion by 10 million. 10 thousand seconds?

What happens if you remove the assignment to the array? The program will be left with an assignment to a single variable. Assignment of a constant value. A decent compiler will notice that all these loops can be thrown away and only one instruction will be left: int = 2.

Remember that a compiler has a right to modify your source code if it decides that it will not change the program's behavior.

zkoza
  • 2,644
  • 3
  • 16
  • 24