为什么打印换行需要这么长时间?这只是我的机器,还是别人看到同样的效果?
使用换行符:
#!/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)
Run Code Online (Sandbox Code Playgroud)
没有换行:
#!/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)
Run Code Online (Sandbox Code Playgroud)
编辑:我想补充说,放置两个"\n"会导致执行时间延长两倍,至少是挂钟秒.
Run Code Online (Sandbox Code Playgroud)timethis 100000: 16 wallclock secs ( 0.15 usr + 0.52 sys = 0.67 CPU) @ 149253.73/s (n=100000)
mob*_*mob 12
我不认为缓冲与它有很大关系.我猜这是因为终端需要在打印换行符时滚动(或打印足够的字符来填充一行).当我将这些函数写入文件或对其进行基准测试时/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
Run Code Online (Sandbox Code Playgroud)
总结:额外冲洗会使性能降低约10%.终端上的额外滚动可将性能降低约50%.
\n
导致这个问题的不是本身.相反,print
OS会缓冲连续调用,直到\n
遇到字符或缓冲区已满.此时,输出缓冲区将刷新到屏幕.将输出刷新到屏幕是一个(相对)昂贵的操作,因此,多次刷新输出缓冲区的循环比在最后只刷新缓冲区一次的循环要慢得多(这种情况在你的程序退出).