Created
July 25, 2015 19:12
-
-
Save davidagold/39c59aa0965af1270af4 to your computer and use it in GitHub Desktop.
`NullityIndex` -- indexing non-empty entries of a `NullableArray`
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
immutable NullityIndex | |
non_nulls::Vector{Int} | |
end | |
function NullityIndex(X::NullableArray) | |
inds = Vector{Int}() | |
sizehint!(inds, length(X.isnull)) | |
for i in eachindex(X.isnull) | |
!X.isnull[i] && push!(inds, i) | |
end | |
return NullityIndex(inds) | |
end | |
# test that 'NullityIndex'es cover all and only the non-null indices of a | |
# `NullableArray` -- returns `true` if success. | |
function test(X::NullableArray) | |
ni = NullityIndex(X) | |
res = true | |
for i in ni.non_nulls | |
res &= !X.isnull[i] | |
end | |
for i in setdiff(eachindex(X.isnull), ni.non_nulls) | |
res &= X.isnull[i] | |
end | |
return res | |
end | |
function f(tup::Tuple{NullableArray, NullityIndex}) | |
X, ni = tup | |
res = Nullable(0.0) | |
for i in ni.non_nulls | |
@inbounds res += X[i] | |
end | |
return res | |
end | |
function g(X::NullableArray) | |
res = Nullable(0.0) | |
for i in eachindex(X) | |
@inbounds !X.isnull[i] && (res += X[i]) | |
end | |
return res | |
end | |
function profile(N::Int) | |
X = NullableArray(rand(N), rand(Bool, N)) | |
ni = NullityIndex(X) | |
print("NullityIndex(X) (~half missing entries, N = $N)") | |
@time NullityIndex(X) | |
a = f((X, ni)) | |
b = g(X) | |
println("f(X) = ", a, " g(X) = ", b) | |
println() | |
print("f (uses NullityIndex): "); @time f((X, ni)) | |
print("g (normal looping): "); @time g(X) | |
nothing | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, this is better: