Make fastmath use optional in a package

Suppose that I write a package in which I would like to give the user the option to use fast math inside the package, but not necessarily elsewhere. What would be the best way of accomplishing that?

The following is one possibility (for addition), but I doubt that it’s optimal. Thoughts?

if haskey( ENV, "foomath" )
    import Base.FastMath.add_fast as +
else
    import Base.+ as +
end

Perhaps Preferences.jl?

3 Likes

While at first glance such a switch seems like good solution, it has one major drawback: dependencies you use in your code won’t be affected by it. That is, functions like sum or various BLAS library functions (* on matrices, for example) will still use the non-fastmath versions. So unless you want to code everything yourself, this will likely result in confusing differences in performance & semantics (“fast math” makes some assumptions about the input data, like not having NaN or Inf, among others).

So, what effect would you like such a switch to have? As is, I’m not sure there is enough information here to give a meaningful answer.

2 Likes

Maybe a conditional macro definition, like

if haskey( ENV, "foomath" )
    macro foomath(expr)
        :(@fastmath $(esc(expr)))
    end
else
    macro foomath(expr)
        esc(expr)
    end
end

In that case, @foomath does nothing unless foomath option is present.

1 Like