Optimizing derivative approximations in IDL
Computing standard derivative approximations that are not included as part of the standard library (The discrete 2D Laplacian for example) can be very time consuming. This Help Article demonstrates how IDL's SHIFT function can be used, in place of a FOR loop, to improve performance when approximating derivatives.
Use the SHIFT function to avoid FOR loops.
Since FOR loops are handled at the interpreter level, they execute slowly in comparison to an equivalent operation that uses an IDL intrinsic function. In the latter case IDL simply packages the information and sends it to an optimized C routine, so only a small amount of overhead is incurred in the process.
Below is an example of a 2d laplacian code using the SHIFT function. The code includes a timing test to compare with the standard FOR-loop formulation. At the chosen resolution, the SHIFT formulation ran up to 100 times faster on certain platforms.
pro ApproximateLaplacian
;Main level program to create
;some random data and compute
;its 2d laplacian, using both
;the SHIFT and LOOP formulations
;and producing timing results
nx=512 & ny=512
f = FLTARR(nx+2,ny+2)
g1 = FLTARR(nx+2,ny+2)
g2 = FLTARR(nx+2,ny+2)
f(1:nx,1:ny) = RANDOMU(seed,nx,ny)
t0 = SYSTIME(1)
;Compute LAPLACIAN
FOR i = 1, nx DO BEGIN
FOR j = 1,ny DO BEGIN
g1(i,j) = f(i+1,j) + f(i-1,j) + $
f(i,j+1) + f(i,j-1) - $
4*f(i,j)
ENDFOR
ENDFOR
t1 = SYSTIME(1)
;Compute LAPLACIAN using SHIFT
g2 = SHIFT(f,-1,0) + SHIFT(f,1,0) + $
SHIFT(f,0,1) + SHIFT(f,0,-1) - $
4*f
t2=SYSTIME(1)
time1 = t1-t0
time2 = t2-t1
;Compare times
PRINT, time1, time2
END