2
$\begingroup$

I'm using my own package, partly based on Ted Ersek's RootSearch package, partly based on some posts on this portal. It has a lot of debug prints coded like this:

If[debug>n, Print[...]];

where n is an integer number (0, 1, 2, ...), controlling how many prints should be activated, and debug is a value passed to the package as the value of XRootDebug option. By default, debug is zero, so the debugging information is suppressed. However I am afraid that lot of If's slow down computation even if they evaluated to False.

Is there a way to automatically remove all such Ifs?

In the early days of the Internet, I knew how to write scripts for such tasks in Windows, but I forgot everything. I mean the script can be run either from Mathematica using its own tools or from Windows using e.g. JavaScript.

$\endgroup$
2
  • 1
    $\begingroup$ it if is all on one line, i.e. the print and the IF also, all on one line, then you can easily do that using something like SED or awk, with some smart regular expression code which will delete any line that contains the string "if[debug" in it. if the debug code is on more than one line, then may be manual way is the only way. You can ask about how to do in a Linux/sed/awk forum? may be even notepad++ can do it, as it also supports regular expressions. $\endgroup$
    – Nasser
    Commented Nov 4, 2022 at 3:38
  • 2
    $\begingroup$ btw, I do not think it will cost any extra time to leave the code there, if you are worrying about cpu time. It might take extra nano second or so. But it might make the code look less readable, yes. I'd worry about this more than about CPU cost. $\endgroup$
    – Nasser
    Commented Nov 4, 2022 at 3:43

1 Answer 1

2
$\begingroup$

I would like to share the pattern I use:

Options[f] = {Verbose -> False};

f[x_, opts : OptionsPattern[]] := 
 If[OptionValue["Verbose"], Identity, QuietEcho][
  Module[{y},
   Echo["Preparing to add 1"];
   y = EchoEvaluation[x + 1];
   Echo[y]
   ]
  ]

By wrapping the whole function with QuietEcho, we can avoid all those ifs. The issue in regards to your question is that it doesn't support multiple levels of verbosity.

$\endgroup$
1
  • $\begingroup$ I measured AbsoluteTiming of your solution with Verbose -> False and Verbose -> True. Some difference is evident: (* {0.084031, 4} vs {0.0000966, 4} *) but physical deleting of all echos yiels much better result: (* {8.2*10^-6, 4} *). Or course, for more complex code this difference might be negligible. $\endgroup$ Commented Nov 5, 2022 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.