Is it the correct way to check for specializations?

Following the last paragraph at docs, I want to check if julia is generating specialized version for some of my code. Testing against some built-in functions, first define

function get_sp(wfx)
    for mi in wfx.specializations
        if !isnothing(mi)
            println(mi)
            println("-"^9)
        end
    end
end

Then, running

exp(1)
exp(rand(3, 3))
exp(rand(Float32, 3, 3))
exp(rand(ComplexF64, 3, 3))

get_sp(@which exp(rand(3, 3)))

shows

MethodInstance for exp(::Matrix{Float64})
---------
MethodInstance for exp(::Matrix{ComplexF64})
---------
MethodInstance for exp(::Matrix{Float32})
---------

while

sin(1)
sin(1.2)
sin(0.3im)
get_sp(@which sin(.3im))

just gives

MethodInstance for sin(::ComplexF64)
---------

Is it then correct to say that, for exp(m) specialzied versions are generated for different types of matrices while no specialized version is generated for different number types to sin(x)?

Thanks!

which returns just one method, and gives the specializations of that one method. In this case, I think you want to check all methods of sin to see what specializations each of them had

1 Like

Beware, though, that which can create specializations. A fairly safe approach is to use the MethodAnalysis package:

julia> using MethodAnalysis

julia> methodinstances(sin)
Core.MethodInstance[]

julia> sin(3)
0.1411200080598672

julia> sin(3.5)
-0.35078322768961984

julia> methodinstances(sin)
2-element Vector{Core.MethodInstance}:
 MethodInstance for sin(::Float64)
 MethodInstance for sin(::Int64)

julia> @which sin(3)
sin(x::Real)
     @ Base.Math math.jl:1488

julia> @which sin(3.5)
sin(x::T) where T<:Union{Float32, Float64}
     @ Base.Math special/trig.jl:29

So you can see it aggregated the specializations across multiple methods, once those specializations were created.

If you start a fresh session and reverse the order, calling @which before the first invocation of methodinstances, you’ll see those specializations already exist—they were created by @which.

3 Likes

Thanks for the package!

if which is to be avoided when looking for specializations, then the documentation needs to be updated. see the last sentence in the section linked to above.