From: Masahiro TANAKA Date: 2002-12-01T19:31:14+09:00 Subject: Re: Numerical Ruby Hi, >From: Olivier Saut > 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 > (http://www.ir.isas.ac.jp/~masa/ruby/index-e.html) 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