Skip to content

Commit

Permalink
Faster cumsum & cumprod. Fixes #7342.
Browse files Browse the repository at this point in the history
  • Loading branch information
timholy committed Jun 21, 2014
1 parent 4e8b3d3 commit 49db40b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 27 deletions.
27 changes: 0 additions & 27 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1408,33 +1408,6 @@ for (f, fp, op) = ((:cumsum, :cumsum_pairwise, :+),
return c
end

@eval function ($f)(A::StridedArray, axis::Integer)
dimsA = size(A)
ndimsA = ndims(A)
axis_size = dimsA[axis]
axis_stride = 1
for i = 1:(axis-1)
axis_stride *= size(A,i)
end

B = $(op===:+ ? (:(similar(A,_cumsum_type(A)))) :
(:(similar(A))))

if axis_size < 1
return B
end

for i = 1:length(A)
if div(i-1, axis_stride) % axis_size == 0
B[i] = A[i]
else
B[i] = ($op)(B[i-axis_stride], A[i])
end
end

return B
end

@eval ($f)(A::AbstractArray) = ($f)(A, 1)
end

Expand Down
21 changes: 21 additions & 0 deletions base/multidimensional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,27 @@ end

eval(ngenerate(:N, nothing, :(setindex!{T}(s::SubArray{T,N}, v, ind::Integer)), gen_setindex!_body, 2:5, false))

cumsum(A::AbstractArray, axis::Integer) = cumsum!(similar(A, Base._cumsum_type(A)), A, axis)
cumprod(A::AbstractArray, axis::Integer) = cumprod!(similar(A), A, axis)

for (f, op) in ((:cumsum!, :+),
(:cumprod!, :*))
@eval begin
@ngenerate N typeof(B) function ($f){T,N}(B, A::AbstractArray{T,N}, axis::Integer)
if size(B, axis) < 1
return B
end
size(B) == size(A) || throw(DimensionMismatch("Size of B must match A"))
@nexprs N d->(isaxis_d = axis == d)
# Copy the initial element along each 1d vector along dimension axis
@inbounds @nloops N i d->(d == axis ? (1:1) : (1:size(A,d))) @nref(N, B, i) = @nref(N, A, i)
@inbounds @nloops N i d->((1+isaxis_d):size(A, d)) d->(j_d = i_d - isaxis_d) begin
@nref(N, B, i) = ($op)(@nref(N, B, j), @nref(N, A, i))
end
B
end
end
end

### from abstractarray.jl

Expand Down

0 comments on commit 49db40b

Please sign in to comment.