代码之家  ›  专栏  ›  技术社区  ›  vol7ron

为什么用Perl打印“\n”要花这么长时间?

  •  9
  • vol7ron  · 技术社区  · 16 年前

    新行:

    #!/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)
    

    没有新线:

    #!/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)
    

    我想补充一点,放置两个“\n”会导致执行 两倍长,至少是挂钟秒。

    timethis 100000: 16 wallclock secs ( 0.15 usr +  0.52 sys =  0.67 CPU) @ 149253.73/s (n=100000)
    
    3 回复  |  直到 16 年前
        1
  •  12
  •   mob    16 年前

    /dev/null ,差别不大。

    use Benchmark;
    timethis(1000000, 'main');
    timethis(1000000, 'main2');
    select STDERR; $| = 0; select STDOUT;  # enable buffering on STDERR
    sub main { print STDERR "you are the bomb. \n" }
    sub main2 { print STDERR "you are the bomb. " }
    
    $ perl benchmark.pl 2> a_file
    timethis 1000000: 21 wallclock secs ( 4.67 usr + 13.38 sys = 18.05 CPU) @ 55410.87/s
    timethis 1000000: 21 wallclock secs ( 4.91 usr + 13.34 sys = 18.25 CPU) @ 54797.52/s
    
    $ perl benchmark.pl 2> /dev/null
    timethis 1000000: 26 wallclock secs ( 2.86 usr + 10.36 sys = 13.22 CPU) @ 75648.69/s
    timethis 1000000: 27 wallclock secs ( 2.86 usr + 10.30 sys = 13.16 CPU) @ 76010.95/s
    
    $ perl benchmark.pl 2> a_file     (without buffering)
    timethis 1000000: 29 wallclock secs ( 3.78 usr + 12.14 sys = 15.92 CPU) @ 62806.18/s
    timethis 1000000: 29 wallclock secs ( 3.27 usr + 12.51 sys = 15.78 CPU) @ 63367.34/s
    
    $ perl benchmark.pl 2> /dev/tty   (window has 35 lines and buffers 10000, YMMV)
    [ 200000 declarations of how you are a bomb deleted ]
    timethis 100000: 53 wallclock secs ( 0.98 usr +  3.73 sys =  4.72 CPU) @ 21190.93/s
    timethis 100000:  9 wallclock secs ( 0.36 usr +  1.94 sys =  2.30 CPU) @ 43535.05/s
    

        2
  •  8
  •   JSBÕ±Õ¸Õ£Õ¹    16 年前

    这不是问题 \n print \不 遇到字符或缓冲区已满。此时,输出缓冲区被刷新到屏幕上。将输出刷新到屏幕是一个(相对)昂贵的操作,因此多次刷新输出缓冲区的循环的性能要比只在最后刷新一次缓冲区的循环慢得多(在程序退出时隐式地发生)。

        3
  •  3
  •   BlueRaja - Danny Pflughoeft    16 年前

    flushes output .

    在大多数stdio实现中,缓冲随输出设备的类型而变化。。。串行设备, ,调制解调器,鼠标和操纵杆,通常是线路缓冲; stdio只有在得到换行符时才会发送整行