Created
February 5, 2018 19:00
-
-
Save ScottPJones/1dbcd665bc442fb76729b62a0f3ab457 to your computer and use it in GitHub Desktop.
Benchmark (fixed) version of `r23` from Discourse, and longer version
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
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