Fortran Allocates / Releases

I have the following question: What is the real overhead for allocating / releasing statements in Fortran90 +? For example, several medium-sized arrays are allocated inside the loop, for example

do i = 1, 1000 allocate(tmp(20)) tmp(1:20) = 1d0 call foo(tmp) deallocate(tmp) end do 

Is it worth allocating one working array based on the maximum size in this case?

+7
source share
2 answers

I found that distributing dynamic arrays within hard loops can really slow down the execution of my code, while valgrind shows that a large percentage of loops are processed by malloc and free . Therefore, if foo is a very fast function, then it is worth statically allocating this array. It's easy to see this overhead by profiling using the callgrind function valgrind (it might be worth reducing the size of your problem, as profiled execution can be at least 10 times slower).

Fortran 2008 has a nicer solution to this problem. You can declare your variables inside a block construct with a size defined at runtime. This should make it easier for the compiler to allocate a variable on the stack. However, I have not used this personally, and I am not sure which compilers support it.

+6
source

The overhead of using ALLOCATE and DEALLOCATE same as the overhead of using malloc() and free() in C. In fact, most Fortran compilers implement (DE)ALLOCATE as wrappers around malloc()/free() with some bookkeeping added. inherent to all Fortran 90 arrays.

It is usually better to isolate a fairly large array of scratches and use it in narrow loops instead of constantly allocating and freeing memory. It also does not allow heaps to fragment, which can lead to distribution problems later (a very rare situation, but this happens, especially with 32-bit codes).

+3
source

All Articles