Skip to content

Performance Difference between argmin and minimum #41963

@Xnartharax

Description

@Xnartharax

I recognised that argmin and minimum perform very differently (at least on my machine):

julia> y = rand(5000)
...
julia> @btime minimum($y)
  856.716 ns (0 allocations: 0 bytes)
0.00017745722529260988
julia> @btime argmin($y)
  5.433 μs (0 allocations: 0 bytes)
4842

Also this very naive implementation is faster than the base library for a Vector{Float64}:

function myargmin(y)
     if isempty(y)
         error("can't supply empty array")
     end
     best_i = 0
     best_e = Inf
     for i=1:length(y)
          if best_e > y[i]
               best_e= y[i]
               best_i = i
           end
     end
     best_i
end
julia> @btime myargmin($y)
  2.156 μs (0 allocations: 0 bytes)
4842

A mapreduce implementation (similar to minimum) has the same performance:

argmin_red((ix, fx), (im, fm)) = fx > fm ? (im, fm) : (ix, fx)
myargmin2(y) = mapreduce(identity, argmin_red, (enumerate(y)))
julia> @btime myargmin2($y)
  2.156 μs (0 allocations: 0 bytes)
(4842, 0.00017745722529260988)

Both implementations are faster than the ones provided in Base.
I think we should be able to rely on the base library to have the best performance for these basic tasks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    foldsum, maximum, reduce, foldl, etc.performanceMust go faster

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions