Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Find a better way of checking allocations/type-instability in unit tests #126

Open
heyx3 opened this issue Feb 2, 2024 · 0 comments
Open
Labels
META:internal Created by Billy SIZE:medium Conceptually easy but bigger in scope/conceptually hard but small in scope/medium in both TYPE:tests Improving unit tests

Comments

@heyx3
Copy link
Owner

heyx3 commented Feb 2, 2024

Check out this code which presumably understands the Julia compiler better than I do:

https://github.com/JuliaObjects/ConstructionBase.jl/blob/master/test/runtests.jl#L427-L451

function hot_loop_allocs(f::F, args...) where {F}
    # we want to test that f(args...) does not allocate 
    # when used in hot loops
    # however a naive @allocated f(args...)
    # will not be representative of what happens in an inner loop
    # Instead it will sometimes box inputs/outputs
    # and report too many allocations
    # so we use Refs to minimize inputs and outputs
    out_ref = Ref(f(args...))
    arg_refs = map(Ref, args)
    write_output_to_ref!(f, out_ref, arg_refs...)
    out_ref = typeof(out_ref)() # erase out_ref so we can assert work was done later
    # Avoid splatting args... which also results in undesired allocs
    allocs = if length(arg_refs) == 1
        r1, = arg_refs
        @allocated write_output_to_ref!(f, out_ref, r1)
    elseif length(arg_refs) == 2
        r1,r2 = arg_refs
        @allocated write_output_to_ref!(f, out_ref, r1, r2)
    else
        error("TODO too many args")
    end
    @assert out_ref[] == f(args...)
    return allocs
end
@heyx3 heyx3 added TYPE:tests Improving unit tests SIZE:medium Conceptually easy but bigger in scope/conceptually hard but small in scope/medium in both labels Feb 2, 2024
@heyx3 heyx3 mentioned this issue Feb 2, 2024
@heyx3 heyx3 added the META:internal Created by Billy label Feb 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
META:internal Created by Billy SIZE:medium Conceptually easy but bigger in scope/conceptually hard but small in scope/medium in both TYPE:tests Improving unit tests
Projects
None yet
Development

No branches or pull requests

1 participant