# Why does having many Print statements slow down my code?

I have a code that I need to debug. I have put a Print[] into it that should give about 10^4 prints for table entries. I know that 10^4 is large, and this exposes the fact that it takes more and more as the number of outputs gets large ... Can anybody explain the reason why it gets so slow as the number of Print[] statements grows?

• How about replacing all instances of Print[] with Sow[] and enclose the entire beast in Reap[]? You can then study the list thus produced at leisure. – J. M.'s ennui May 25 '15 at 15:44
• @Guesswhoitis. But usually you do want to see the output of Print during execution time, and often not just the current one (then of course a simple Dynamic[printoutput] would be enough. – Rolf Mertig May 25 '15 at 16:27
• Okay; does PrintTemporary[] also incur a speed penalty when used? – J. M.'s ennui May 25 '15 at 16:30
• @Rolf You'd want to see 10^4 Print[] instances in real time during execution? If the volume of log entries is enough that it clogs up the Front End, you almost certainly don't want to examine them visually. Sow[] or file-based solutions like yours will get that data where you need it, in a machine-readable form which is likely more useful, without you needing to actually see it. – Emilio Pisanty May 25 '15 at 23:07
• @episanty Quiero ver todo! – Rolf Mertig May 26 '15 at 10:44

As to why I do not know. Maybe the FrontEnd is too inefficient in creating thousands of output cells. Maybe people do not do this and use WriteString instead. E.g. this evaluates in 0.6 seconds on my machine

$startTime = AbsoluteTime[]; Do[mybigfun[i]; WriteString["stdout", " \n", {i, Date[]}], {i, 10^4}]; AbsoluteTime[] -$startTime


while this

$startTime = AbsoluteTime[]; Do[mybigfun[i]; Print[{i, Date[]}], {i, 10^4}]; AbsoluteTime[] -$startTime


needs 63 seconds.

And yes, I also think that the overhead of the standard notebook FrontEnd is too much. You could use Wolfram Workbench then, once it will be released to the general public for Mathematica 10. Or you use the Text-based interface until then.

• Dear Rolf, thanks a lot for this tip. The WriteString thing takes 1.6 seconds here, the Print one has stuck my laptop and has been going on for minutes now, as it did before in my actual program. Thanks a lot for your comment and for helping out! – Rho Phi May 25 '15 at 18:36
• Dear Roberto: Prego. I get very very annoyed by some FrontEnd inefficiencies, but often there is a way around such trouble. – Rolf Mertig May 25 '15 at 19:17