Search code examples
matlabconditional-statementsprocessing-efficiency

How expensive are debug conditional statements?


I am developing a combinatorial optimisation algorithm in MATLAB, and I have a bunch of conditional statements that basically just check flags that when set to true will print the value of some variable or show a figure of current progress or state of the system so I can see what is happening if something goes wrong or I need to check it.

I was just wondering how expensive these conditional statements actually are in the scheme of things?

I wouldn't normally worry about it, but there are quite a few of them in the code and the whole thing executes around 20-50,000 times per run for large problem instances, so that is probably at least a million extra "if" statements per run that, while evaluating to false, must have some overhead.

Or are they just so fast that it doesnt really matter? A run may take up to 40 seconds to a minute sometimes. So id imagine it is only a very small fraction of that.

Should I comment them out instead of using flag variables?


Solution

  • You Mention that the program runs this code 20-50000 times and you may have a million extra if statements because of that. The thing to keep in mind is the relative overhead. An if statement may be significant if there is limited overhead in the rest of your code. Heres some dirty simple code to examine:

    for aa=1:10000
        a=1+1;
        if a~=2
            pause
        end
    end
    

    when this is profiled: Lines where the most time was spent

    7 end     10000 0.043s  40.0%
    4 if a~=2 10000 0.043s  40.0%
    3 a=1+1;  10000 0.021s  20.0%
    

    In this really simply case, even though the if statement returns false, it takes twice as long as the simple addition. Obviously though, it isnt a whole load of impact in the human scale sense of time. You can try to profile your code and see the impact of the checks. Better yet, you can create a duplicate code but without the checks to really see the impact. Finally, the overall runtime of the code may not be overly important in the grand scheme of things. If this is time sensitive, I would offer that matlab may not be the best option. If you are simply looking to improve existing code. I have often found that commenting out the debug checks (for knowledgeable users) and only uncommenting them when the function crashes, to find the bug.

    please post an example, or some profiles code so we can see whether any of the above applies in your case.