Skip to content

Commit

Permalink
Improve efficiency of minimum(::Diagonal)
Browse files Browse the repository at this point in the history
julia> DM = Diagonal(rand(100));

julia> @Btime minimum($DM);    # before
  27.987 μs (0 allocations: 0 bytes)

julia> @Btime minimum($DM);    # after
  246.091 ns (0 allocations: 0 bytes)
  • Loading branch information
jlapeyre committed Dec 2, 2018
1 parent 413fc47 commit b0d1479
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
6 changes: 6 additions & 0 deletions stdlib/LinearAlgebra/src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ function size(D::Diagonal,d::Integer)
return d<=2 ? length(D.diag) : 1
end

function Base.minimum(D::Diagonal{T}) where T <: Number
mindiag = minimum(D.diag)
size(D, 1) > 1 && return (min(zero(T), mindiag))
return mindiag
end

@inline function getindex(D::Diagonal, i::Int, j::Int)
@boundscheck checkbounds(D, i, j)
if i == j
Expand Down
5 changes: 5 additions & 0 deletions stdlib/LinearAlgebra/test/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ Random.seed!(1)
for func in (det, tr)
@test func(D) func(DM) atol=n^2*eps(relty)*(1+(elty<:Complex))
end

if eltype(D) <: Real
@test minimum(D) minimum(DM)
end

if relty <: BlasFloat
for func in (exp, sinh, cosh, tanh, sech, csch, coth)
@test func(D) func(DM) atol=n^3*eps(relty)
Expand Down

0 comments on commit b0d1479

Please sign in to comment.