Why do `@allocated` and `Profile.Allocs.@profile` give different results?

The number of allocations reported by Profile.Allocs.@profile agrees with @allocations, but the total number of bytes allocated differs from @allocated for some reason:

using Profile.Allocs

f(n) = sum(2*collect(1:n))

function g(n)
    println(@allocations(f(n)), " allocs: ", @allocated(f(n)), " bytes")
    Allocs.clear()
    Allocs.@profile sample_rate = 1.0 f(n)
    allocs = Allocs.fetch().allocs
    b = sum(a -> a.size, allocs)
    println(length(allocs), " allocs: ", b, " bytes")
end

gives

julia> g(1)
4 allocs: 128 bytes
4 allocs: 112 bytes

julia> g(2)
4 allocs: 160 bytes
4 allocs: 128 bytes

julia> g(100)
4 allocs: 1856 bytes
4 allocs: 1696 bytes

What’s the reason for this discrepancy?

(Tested on Julia 1.11.8, 1.12.4 and 1.13.0-alpha2.)

1 Like