Best practice for assertions for debugging purposes

Hi there!
I’m building a package and have started to use asserts in all my functions that check dimensions of the function arguments.
As most of these functions are called from my own code only, these asserts should not be there once I’m finished.
To this end I have enclosed them with
@static if(debugging_mode==true)

end

so that the debugging_mode variable is checked during compilation but not anymore during runtime. Looking into the generated llvm code made me believe so.
The problem is, that it is difficult to change the variable and force a recompilation. The only way I found reliable was to restart Julia.
Therefore my question ist: How should I make these assertions (or should i use a different mechanism) so that I can switch them on and off during compile time and how do I then force recompilation of my functions?
(In case you wonder: I’m using Revised but it doesn’t help here)

1 Like

Or just copy the trick from there: use a function that just returns true, then redefine it to false to turn off asserts. That will force recompilation of functions that use that function.

7 Likes

Thanks for the hint!

For future reference: Using a function works only, when NOT declaring the if as @static.
But diggin into it a little I found that the compiler realizes on its own that the if statement can be resolved at compile time and will remove the code enclosed in an if branch that is not followed.
The code I used in the end was:

function mydebugging()
    return true
end

and in the functions themselves:

function multiply(M,xi)
    # assert the input dimensions:
    if(mydebugging())
        @assert(size(M)==(2,2))
        @assert(size(xi)==(2,))
    end
    return M*xi
end

The @code_llvm macro was helpful!

1 Like

Another idea, if your arrays are small and statically sized (as in your example, where they have to be 2 x 2 is to use StaticArrays.jl.
This will let you use types to constrain their size. Given that the arrays are small, StaticArrays should also improve performance.

1 Like

That made quite the speedup, thanks!