Last active
June 28, 2016 02:16
-
-
Save axsk/b4cf5e8c24a351e00874c624bfcf7dc4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias ColVec Vector{Union{Colon,Int}} | |
immutable SliceIterator{A<:AbstractArray} | |
a::A | |
dim::Int | |
cols::ColVec | |
end | |
function SliceIterator(a, dim::Int) | |
cols = ColVec(length(size(a))) | |
cols = fill!(cols, :) | |
SliceIterator(a, dim, cols) | |
end | |
Base.length(itr::SliceIterator) = size(itr.a,itr.dim) | |
Base.size(itr::SliceIterator) = (length(itr),) | |
Base.start(itr::SliceIterator) = 1 | |
Base.done(itr::SliceIterator, i::Int) = i > length(itr) | |
function Base.next(itr::SliceIterator, i::Int) | |
itr.cols[itr.dim] = i | |
slice(itr.a, itr.cols...), i+1 | |
end | |
using BenchmarkTools | |
A=rand(100,100) | |
mycollect(a) = [a[i,:] for i in 1:size(a,1)] | |
@show @benchmark collect(A) # (unfair) baseline | |
@show @benchmark mycollect(A) # simple implementation | |
@show @benchmark collect(SliceIterator(A, 1)) # slow one :( |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment