After debugging my MATLAB code, I'd like to be able to turn off assertions to get a bit of extra speed if possible. (The expression inside the assertion is very short and quick, but there are a lot of calls inside tight loops, so it adds up. Yes, I profiled.) How do I do that globally in MATLAB? I'm looking for something akin to defining NDEBUG in C/C++, or enabling optimization in Python, or -disableassertions flag in Java. Find/replace of assert( with %assert( is too ugly for my taste.
It occurred to me after posting these solutions that while effectively disabling assertions, they don't prevent execution of the expression. Perhaps you could exploit short-circuiting of logical expressions (true || expr) to avoid evaluating expr. This could be done by using a global NDEBUG in place of that true. That is, use assert(NDEBUG || expr) so that expr won't be evaluated when NDEBUG is true. For example,
% parentCode.m (or typed on command prompt)
global NDEBUG; NDEBUG=true;
testassertions % test script below
% testassertions.m
global NDEBUG
if isempty(NDEBUG), NDEBUG=false; end
assert(NDEBUG || fprintf('NO\n')==2) % did fprintf write 3 characters? (no, 4)
disp('Assertions are off!')
To use this approach, you would oviously need to modify your assert calls to use the (NDEBUG || expr) approach, and you would add the two lines to bring in the global, as done in testassertions.m above. This is not the "switch" you are looking for, but it would avoid computing expr, which seems to be the real goal here.
assert.m
You can override assert with your own assert.m at the top of your path. Just use varargin and it will work:
function assert(varargin)
end
The first time you run it or rehash your path, you get a warning, then it's fine!
>> assert(false)
>> assert(false,'No error here',[])
>>
No errors, no warnings.
assert
Possibly easier to manage is an anonymous assert function with variable inputs and no outputs:
assert = @(varargin) deal;
Here we are using deal with no inputs (nargin=0) because it just does varargout = varargin;.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With