Force calling the generic for benchmarking

Consider the following dummy example:

function f(x)
    println("We called the generic")
    prod(x)
end
function f(x::Real)
    println("We called the method")
    x
end

# Some checks: 
f(1)
f([1 2])

How can I force f(1) to run the generic, to compare it’s performance w.r.t the specialized method ? (using e.g. @btime) ?

I’d like to benchmark my generic function f against the specialized methods to be sure that they are worth it: they return the same thing as the generic, just written in an hopefully faster way. If the time gain is not effective, i might just remove these methods and simplify my package.

1 Like

You can use the invoke function for this, i.e.,

invoke(f, Tuple{Any}, 1)

will call the generic f(::Any) method with the argument 1. In Julia 1.7 you will be able to use the simpler syntax Base.@invoke f(1::Any).

5 Likes