My code uses lots of loops as in the following example.
def faraday
for y in 1..(maxY-1)
for z in 1..(maxZ-1)
@Bx[y,z]+=-(dt/dy)*(@Ez[y+1,z]-@Ez[y,z])+(dt/dz)*(@Ey[y,z+1]-@Ey[y,z])
@By[y,z]+= - (dt/dz)*(@Ex[y,z+1]-@Ex[y,z])
@Bz[y,z]+=(dt/dy)*(@Ex[y+1,z]-@Ex[y,z])
end
end
end
I am using NArray from Masahiro Tanaka
to represent the electromagnetic field.
Is there any way to speed up this type of computations? (I am not sure
how a C extension could help in this case.)
If you use NArray, "writing without loop" is the way to speed up.
Your 'faraday' method can be rewritten as:
def faraday2
dt,dx,dy,dz = [1.0]*4
@Bx[1..-2,1..-2] += -(dt/dy)*(@Ez[2..-1,1..-2] - @Ez[1..-2,1..-2]) +
(dt/dz)*(@Ey[1..-2,2..-1] - @Ey[1..-2,1..-2])
@By[1..-2,1..-2] += -(dt/dz)*(@Ex[1..-2,2..-1] - @Ex[1..-2,1..-2])
@Bz[1..-2,1..-2] += (dt/dy)*(@Ex[2..-1,1..-2] - @Ex[1..-2,1..-2])
end
For 500x500 array, the result of benchmark on my machine is:
- with loop: 8.69 sec
- without loop: 0.31 sec
Regards,
Masahiro Tanaka
-- DaleBrayden - 01 Dec 2002