Alex Rivera | Logout

Why does it take so long to print "\n" in Perl?

Asked 2010-06-23T18:40:35.913
9

Why does it take so long to print a newline? Is this just my machine, or do others see the same effect?

With the newline:

#!/usr/bin/perl

use strict;
use Benchmark;

   timethis(100000,'main();');


   sub main {
      print "you are the bomb. \n";
   }


   # outputs: 
   # timethis 100000:  8 wallclock secs ( 0.15 usr +  0.45 sys =  0.60 CPU) @ 166666.67/s (n=100000)

W/o the newline:

#!/usr/bin/perl

use strict;
use Benchmark;

   timethis(100000,'main();');


   sub main {
      print "you are the bomb. ";
   }


   # outputs:
   # timethis 100000:  0 wallclock secs ( 0.09 usr +  0.04 sys =  0.13 CPU) @ 769230.77/s (n=100000)
   #     (warning: too few iterations for a reliable count)

Edit: I'd like to add that placing two "\n" causes the execution to take twice as long, at least for wallclock seconds.

timethis 100000: 16 wallclock secs ( 0.15 usr +  0.52 sys =  0.67 CPU) @ 149253.73/s (n=100000)
Edit
Report

1 Answer

8

It's not the \n per se that causes this problem. Rather, successive calls to print are buffered by the OS until the \n character is encountered or the buffer is full. At that point, the output buffer is flushed to the screen. Flushing the output to the screen is a (relatively) expensive operation, so the loop in which you flush the output buffer many times has much slower performance than the loop in which you only flush the buffer once at the end (which happens implicitly when your program exits).

answered 2010-06-23T18:44:57.237

Your Answer