On Mar 4, 2005, at 8:47 AM, Suresh Seetharam wrote:
> I had a question regarding the efficiency of 3D matrices...
...
> I attach an extract from my code here. [most code elided]
...
> do i = 1, flowindx(4)-r
> do j = 1, nnelt
> do l = 1, nnelt
> K(m+i,j,l) = K(m+i,j,l) + cdd * Ki(j,l) &
> & * constkcdcd(i+1)
> end do
> end do
> end do
Your problem has little to do with the arrays being 3D. It has
*EVERYTHING* to do with memory access patterns. This issue comes up
also with 2D arrays. Memory-related issues are very big deals with
today's computers.
To cut to the short answer, what you need to do is reverse the nesting
of the above 3 loops. That is, you want it to look more like
do l = 1, nnelt
do j = 1, nnelt
do i = 1, flowindx(4)-r
K(m+i,j,l) = K(m+i,j,l) + cdd * Ki(j,l) &
& * constkcdcd(i+1)
end do
end do
end do
(Probably. I haven't carefully studied what is happening enough to make
sure that this actually does the same thing).
In general, you want to make innermost loops be on the leftmost index
of arrays; this plays well with the way that memory management works.
Of course, sometimes you can't trivially write algorithms that way, in
which case things get more complicated.
A sufficiently "smart" compiler might be able to re-order the loops for
you as an optimization, but it doesn't hurt to write them that way in
the first place (and it can help a lot if the compiler isn't so smart
or if you haven't asked it for that level of optimization).
I don't know enough about the compiler-specific aspects to comment; the
above comments are very general.
--
Richard Maine | Good judgment comes from experience;
[log in to unmask] | experience comes from bad judgment.
| -- Mark Twain
|