How do I precompile a callable struct?

I have something like:

struct S end
(::S)() = true

I think precompile(A, ()) would precompile the consstructor A, right?

How do I precompile (::S)()?

I there a way to verify whether a function has been precompiled? This is what I have come across:

using MethodAnalysis: methodinstance
methodinstance(S, ())

Haven’t tried it, but I would assume precompile(A(), ()) would do it!

2 Likes

I’ve tried that. But MethodAnalysis.methodinstance(A(), ()) returns nothing.

Can get to my computer right now, but what about A.instance?

julia> precompile(A.instance, ())
true

julia> methodinstance(A.instance, ()) isa Nothing
true

It works when the type subtypes Function:

julia> using MethodAnalysis

julia> struct S <: Function end

julia> (::S)() = 7

julia> precompile(S(), ())
true

julia> methodinstance(S(), ())
MethodInstance for (::S)()

I notice that MethodAnalysis.jl dispatches on Base.Callable (Union{Function,Type}) in some places. Maybe make a PR?

1 Like

First session without precompile:

julia> struct S end; (::S)() = true

julia> methods(S())[1].specializations
svec()

julia> s1=S(); @time s1()
  0.000261 seconds (306 allocations: 22.656 KiB, 85.21% compilation time)
true

julia> methods(S())[1].specializations
MethodInstance for (::S)()

julia> s2=S(); @time s2()
  0.000008 seconds
true

Second session with precompile

julia> struct S end; (::S)() = true

julia> methods(S())[1].specializations
svec()

julia> precompile(S(), ())
true

julia> methods(S())[1].specializations
MethodInstance for (::S)()

julia> s1=S(); @time s1()
  0.000009 seconds
true

@timeing in a let block however makes the compilation time report go away; I think that’s the let block being compiled at top-level before execution because the docstring-suggested @time @eval recovers the report, not sure though.

1 Like

Does this mean that S must be a subtype of Function in order to precompile? Or is that just to make MethodAnalysis.methodinstances work?

precompile(S(), ()) was always returning true. It’s just I didn’t know what I was precompiling and was looking for a way to check.

The latter.

Got it. I also just saw @Benny’s solution.

MasonProtter has opened an issue:

1 Like