在阅读“ Intermediate Perl ”一书时,我注意到了关于 Schwartzian 变换的部分并尝试了练习中的示例(9.9.2),但注意到多次运行导致变换比正常排序花费更多时间。此处的代码根据文件大小对 windows\system32 目录中的文件进行简单排序 -
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark;
my $time = timethese( 10, {
testA => sub { map $_->[0],
sort {$a->[1] <=> $b->[1]}
map [$_, -s $_],
glob "C:\\Windows\\System32\\*";
},
testB => sub { sort { -s $a <=> -s $b } glob "C:\\Windows\\System32\\*";
},
}
);
输出是 -
Benchmark: timing 10 iterations of testA, testB...
testA: 11 wallclock secs ( 1.89 usr + 8.38 sys = 10.27 CPU) @ 0.97/s (n=10)
testB: 5 wallclock secs ( 0.89 usr + 4.11 sys = 5.00 CPU) @ 2.00/s (n=10)
我的理解是,由于文件操作(-s)需要在 testB 案例中一遍又一遍地重复,它的运行速度应该比 testA 慢很多。输出虽然偏离了该观察。我在这里想念什么?