Skip to content

Instantly share code, notes, and snippets.

@ScottPJones
Created Feb 5, 2018
Embed
What would you like to do?
Benchmark (fixed) version of `r23` from Discourse, and longer version
using BenchmarkTools
function r23(obs, mod)
bis = (!isnan).(obs) .& (!isnan).(mod); # == !isnan.(obs.*mod)
dobs = obs[bis] .- mean(obs[bis])
dmod = mod[bis] .- mean(mod[bis])
sum((dobs .* dmod)) / sqrt( sum((dobs .^ 2)) * sum((dmod .^ 2)) )
end
function spj(obs, mod)
len = length(obs)
totobs = zero(eltype(obs))
totmod = zero(eltype(mod))
cnt = 0
for i = 1:len
obsval = obs[i]
modval = mod[i]
(isnan(obsval) || isnan(modval)) && continue
cnt += 1
totobs += obsval
totmod += modval
end
meanobs = totobs/cnt
meanmod = totmod/cnt
summul = zero(typeof(meanobs*meanmod))
sumobs = zero(typeof(meanobs))
summod = zero(typeof(meanmod))
for i = 1:len
obsval = obs[i]
modval = mod[i]
(isnan(obsval) || isnan(modval)) && continue
dobs = obsval - meanobs
dmod = modval - meanmod
summul += (dobs * dmod)
sumobs += dobs^2
summod += dmod^2
end
summul / sqrt(sumobs * summod)
end
randvec(n) = [(rand(0:9) == 0 ? NaN : rand()) for i=1:n]
const obs = randvec(10000)
const mod = randvec(10000)
@btime r23(obs, mod)
@btime spj(obs, mod)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment