Skip to content

Using wrong loop order #136

@dcelisgarza

Description

@dcelisgarza

Hi, I'm using the package primarily for its moving averages. I found that pretty much every single case uses the wrong loop order for best performance. The fix is pretty easy, ie just swap the inner and outer loops. For example, this function in movingaverages.jl.

function sma(ta::TimeArray, n::Integer)
  tstamps = timestamp(ta)[n:end]

  vals = zeros(size(values(ta),1) - (n-1), size(values(ta),2))
  for i in 1:size(values(ta),1) - (n-1)
    for j in 1:size(values(ta),2)
      vals[i,j] = nanmean(values(ta)[i:i+(n-1),j])[1]
    end
  end

  cname = Symbol[]
  cols  = colnames(ta)
  for c in 1:length(cols)
    push!(cname, Symbol(string(cols[c], "_sma_", n)))
  end

  TimeArray(tstamps, vals, cname, meta(ta))
end

would simply turn into

function sma(ta::TimeArray, n::Integer)
  tstamps = timestamp(ta)[n:end]

  vals = zeros(size(values(ta),1) - (n-1), size(values(ta),2))
  for j in 1:size(values(ta),2)
    for i in 1:size(values(ta),1) - (n-1)
      vals[i,j] = nanmean(values(ta)[i:i+(n-1),j])[1]
    end
  end

  cname = Symbol[]
  cols  = colnames(ta)
  for c in 1:length(cols)
    push!(cname, Symbol(string(cols[c], "_sma_", n)))
  end

  TimeArray(tstamps, vals, cname, meta(ta))
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions