JuliaLang / PrecompileTools.jl

Reduce time-to-first-execution of Julia code
MIT License
209 stars 13 forks source link

Still have some compilation time #26

Open gitboy16 opened 1 year ago

gitboy16 commented 1 year ago

Hi, It seems as PrecompileTools does not "work" in the following case. By that I mean that compilatiin still hqppen before running the function. Please see below:

module MSort

using PrecompileTools

function quicksort(
    v::Vector{T};
    lo::Int = 1,
    hi::Int = length(v),
) where {T <: Union{Int64, Float64}}
    x = copy(v) 
    quick!(x, lo, hi)
    x
end

function partition(
    xp::Vector{T},
    pivot::T,
    left::Int,
    right::Int,
) where {T <: Union{Int64, Float64}}
    while left <= right
        while xp[left] < pivot
            left += 1
        end
        while pivot < xp[right]
            right -= 1
        end
        if left <= right
            xp[left], xp[right] = xp[right], xp[left]
            left += 1
            right -= 1
        end
    end
    left, right
end

function quick!(
    xp::Vector{T},
    i::Int,
    j::Int,
) where {T <: Union{Int64, Float64}}
    if j > i
        left, right = partition(xp, xp[(j+i)>>>1], i, j)
        quick!(xp, i, right)
        quick!(xp, left, j)
    end
end

@setup_workload begin 
    @compile_workload begin
        quicksort(rand(64))
    end
end

end

x = rand(64); @time Msort.quicksort(x);
# 0.004929 seconds (29 allocations: 2.047 KiB, 99.56% compilation time)

However if I replace Vector{T} by Vector{Float64}, and remove all T in the code, then it works.

Is that expected that compilation happen in the first version ? If yes, could we have PrecompileTools work with parametric type? If no, I suppose it is a bug?

Thank you

NHDaly commented 11 months ago

I can confirm this MRE:

julia> VERSION
v"1.9.2"

(@v1.9) pkg> generate ~/tmp/MSort
  Generating  project MSort:
    ~/tmp/MSort/Project.toml
    ~/tmp/MSort/src/MSort.jl

shell> vim ~/tmp/MSort/src/MSort.jl  # copy in the example

(@v1.9) pkg> activate ~/tmp/MSort
  Activating project at `~/tmp/MSort`

(MSort) pkg> add PrecompileTools
   Resolving package versions...
    Updating `~/tmp/MSort/Project.toml`
  [aea7be01] + PrecompileTools v1.2.0
    Updating `~/tmp/MSort/Manifest.toml`
  [aea7be01] + PrecompileTools v1.2.0
  [21216c6a] + Preferences v1.4.1
  [ade2ca70] + Dates
  [de0858da] + Printf
  [fa267f1f] + TOML v1.0.3
  [4ec0a83e] + Unicode
Precompiling project...
  1 dependency successfully precompiled in 1 seconds. 2 already precompiled.

julia> using MSort

julia> x = rand(64); @time MSort.quicksort(x);
  0.001817 seconds (29 allocations: 2.047 KiB, 99.45% compilation time)

julia>