Skip to content

Instantly share code, notes, and snippets.

@timholy
Last active December 14, 2015 15:29
Show Gist options
  • Save timholy/5108548 to your computer and use it in GitHub Desktop.
Save timholy/5108548 to your computer and use it in GitHub Desktop.
Test file for Iterator2D
function test(m, n, k)
A = randn(m, n)
@time begin
s = 0.0
for j = 1:k
for i = 1:length(A)
s += A[i]
end
end
end
try
gc_disable()
@time begin
s = 0.0
for j = 1:k
for i = Iter.Iterator(A)
s += A[i]
end
end
end
finally
gc_enable()
end
end
test(10, 10, 1)
@sprofile test(1000, 1001, 1)
abstract IteratorState
import Base.assign, Base.done, Base.next, Base.ref, Base.start
immutable Iterator1D
ni::Int
stridei::Int
first_index::Int
end
immutable Iterator1DState <: IteratorState
i::Int
index::Int
end
start(iter::Iterator1D) = Iterator1DState(1, iter.first_index)
next(iter::Iterator1D, state::Iterator1DState) = state, Iterator1DState(state.i+1, state.index + iter.stridei)
done(iter::Iterator1D, state::Iterator1DState) = state.i > iter.ni
immutable Iterator2D
ni::Int
nj::Int
stridei::Int
stridej::Int
first_index::Int
end
immutable Iterator2DState <: IteratorState
i::Int
j::Int
index::Int
end
start(iter::Iterator2D) = Iterator2DState(1, 1, iter.first_index)
next(iter::Iterator2D, state::Iterator2DState) = (state.i+1 <= iter.ni) ? (state, Iterator2DState(state.i+1, state.j, state.index + iter.stridei)) : (state, Iterator2DState(1, state.j+1, iter.first_index+state.j*iter.stridej))
done(iter::Iterator2D, state::Iterator2DState) = state.j > iter.nj
ref(A::StridedArray, state::IteratorState) = parent(A)[state.index]
parent(A::Array) = A
parent(A::SubArray) = A.parent
first_index(A::Array) = 1
first_index(A::SubArray) = A.first_index
function test{T}(A::Array{T}, k)
gc_disable()
@time begin
s = zero(T)
for j = 1:k
for i = 1:length(A)
s += A[i]
end
end
end
@time begin
s2 = zero(T)
for j = 1:k
for i = Iterator2D(size(A,1), size(A,2), 1, size(A,1), 1)
# for i = Iterator1D(length(A), 1, 1)
s2 += A[i]
end
end
end
@assert s == s2
@show s
gc_enable()
end
test(randn(10,11), 1)
println()
@sprofile test(randn(1000,1001), 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment