Skip to content

Instantly share code, notes, and snippets.

@ScottPJones
Created February 5, 2018 19:00
Show Gist options
  • Save ScottPJones/1dbcd665bc442fb76729b62a0f3ab457 to your computer and use it in GitHub Desktop.
Save ScottPJones/1dbcd665bc442fb76729b62a0f3ab457 to your computer and use it in GitHub Desktop.
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