I’m trying to compute the median of a 3D image along the :position
axis, but I found copying the slice is way faster than a view? Why is that? The two functions below are identical expect for one has a copy operation versus a view operation
using AxisArrays
using Images
using BenchmarkTools
img = AxisArray(rand(1024, 1024, 9), :x, :y, :position)
function medianview(arr::AxisArray{T}) where {T}
xydims = map(x->axisvalues(arr)[axisdim(arr, x)], (Axis{:y}, Axis{:x}))
med = AxisArray(zeros(T, length.(xydims)...), :x, :y)
for iter in CartesianRange(xydims)
med[iter] = median(view(arr, iter, :))
end
med
end
function mediancopy(arr::AxisArray{T}) where {T}
xydims = map(x->axisvalues(arr)[axisdim(arr, x)], (Axis{:y}, Axis{:x}))
med = AxisArray(zeros(T, length.(xydims)...), :x, :y)
for iter in CartesianRange(xydims)
med[iter] = median(arr[iter, :])
end
med
end
Any thoughts on why there is such a big difference between the two? And it appears as though view
allocates more memory than copy, which is really weird.
@benchmark medianview(img)
BenchmarkTools.Trial:
memory estimate: 1.47 GiB
allocs estimate: 62407718
--------------
minimum time: 16.194 s (1.41% GC)
median time: 16.194 s (1.41% GC)
mean time: 16.194 s (1.41% GC)
maximum time: 16.194 s (1.41% GC)
--------------
samples: 1
evals/sample: 1
@benchmark mediancopy(img)
BenchmarkTools.Trial:
memory estimate: 536.03 MiB
allocs estimate: 10487846
--------------
minimum time: 611.938 ms (11.08% GC)
median time: 637.819 ms (11.07% GC)
mean time: 648.798 ms (13.06% GC)
maximum time: 747.560 ms (25.30% GC)
--------------
samples: 8
evals/sample: 1