Skip to content

Remove metric fields #22

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

Merged
merged 1 commit into from
Jan 15, 2020
Merged

Conversation

devmotion
Copy link
Member

It seems the metric fields are not needed, it is sufficient to define the metric(::Kernel) trait.

@theogf
Copy link
Member

theogf commented Jan 15, 2020

Doesn't it create unnecessary allocations ?
Maybe an alternative would be to create const objects of each metric in the package.

const m_sqeuclidean = SqEuclidean()
metric(::SqExponential) = m_sqeuclidean

@devmotion
Copy link
Member Author

I just assumed the compiler is smart enough (and the implementation in Distances.jl would be different otherwise) 😄 To be sure that there are no allocations, I used the following benchmark script:

using Distances
using BenchmarkTools

struct A
    metric::SqEuclidean
end

A() = A(SqEuclidean())

metric(::A) = SqEuclidean()

const SQEUCLIDEAN = SqEuclidean()
metric_const(::A) = SQEUCLIDEAN

evaluate_field(a::A, x, y) = evaluate(a.metric, x, y)
evaluate_function(a::A, x, y) = evaluate(metric(a), x, y)
evaluate_const(a::A, x, y) = evaluate(metric_const(a), x, y)

function test(N::Int)
    a = A()
    x = rand(N)
    y = rand(N)

    @btime evaluate_field($a, $x, $y)
    @btime evaluate_function($a, $x, $y)
    @btime evaluate_const($a, $x, $y)

    nothing
end

I got the following results:

julia> test(10_000)
  1.778 μs (0 allocations: 0 bytes)
  1.783 μs (0 allocations: 0 bytes)
  1.785 μs (0 allocations: 0 bytes)

julia> test(100_000)
  23.819 μs (0 allocations: 0 bytes)
  23.808 μs (0 allocations: 0 bytes)
  23.824 μs (0 allocations: 0 bytes)

So the approach shouldn't introduce any allocations.

@theogf
Copy link
Member

theogf commented Jan 15, 2020

Thanks a lot for making all the benchmarks and your contribution!

@theogf theogf merged commit b6e7915 into JuliaGaussianProcesses:master Jan 15, 2020
@devmotion devmotion deleted the metric branch January 15, 2020 18:28
@theogf theogf mentioned this pull request Jan 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants