# 数组循环优化

#1

``````x = range(0.0, 1.0, length=10000)
y = 0.5:0.5:1.5
z = 0.5:0.5:1.5
var = zeros(10000,3,3,3)

function foo(hx::StepRangeLen,hy::StepRangeLen,hz::StepRangeLen,
var::Array{Float64,4})::Array{Float64,3}

siz = size(var)::NTuple{4,Int64}

px = zeros(Float64,siz[1:3]...)
qy = zeros(Float64,siz[1:3]...)
rz = zeros(Float64,siz[1:3]...)

n = size(hx,1)
# Right now do nothing for the ghost cells maybe needed later!
# Take central differences on interior points
if n > 2
@time for k=1:siz[3], j=1:siz[2], i=1:n-2
px[i+1,j,k] = (var[i+2,j,k,1] - var[i,j,k,1])/(hx[i+2] - hx[i])
end
@time @. px[2:n-1,:,:] = (var[3:n,:,:,1] - var[1:n-2,:,:,1])/(hx[3:n] - hx[1:n-2])
end

px
end

px = foo(x,y,z,var);
``````

``````px = foo(x,y,z,var);
0.006217 seconds (175.37 k allocations: 2.676 MiB)
0.001222 seconds (18 allocations: 1.374 MiB)
``````

#2

``````@macroexpand @. px[2:n-1,:,:] = (var[3:n,:,:,1] - var[1:n-2,:,:,1])/(hx[3:n] - hx[1:n-2])
``````

#3

loop-over-array-optimization

#4

#5
``````@views @. px[2:n-1,:,:] = (var[3:n,:,:,1] - var[1:n-2,:,:,1])/(hx[3:n] - hx[1:n-2])
``````

#6