- 论坛徽章:
- 0
|
Interesting - it is the fastest way too. And if you pre allocate the array, it can even be a little bit faster.
- #!/usr/bin/perl
- use strict;
- use warnings;
- use 5.010;
- use Benchmark;
- our @x = ();
- for (1..1000000) {
- push @x, int($_ * rand);
- }
- sub my_copy {
- my @y = @x;
- }
- sub my_return {
- \@x;
- }
- sub extract1 {
- my @y = @x;
- $#y = 1000000;
- @y = @y[@y*0.25 .. @y*0.75];
- return \@y;
- }
- sub extract2 {
- my @y = @x;
- $#y -= 250000;
- @y = reverse @y;
- $#y -= 250000;
- @y = reverse @y;
- return \@y;
- }
- sub extract3 {
- my @y = @x;
- my $count = scalar @y;
- my $start = int(0.25 * $count);
- my $end = int(0.75 * $count);
- my $len = $end - $start;
- @y = splice(@y, $start, $len);
- return \@y;
- }
- sub extract4 {
- my @y = @x;
- $#y = 500000;
- my $count = scalar @y;
- my $start = int(0.25 * $count);
- my $end = int(0.75 * $count);
- my $len = $end - $start;
- @y = splice(@y, $start, $len);
- return \@y;
- }
- my $code = {
- my_copy => q| my_copy() |,
- extract1 => q| extract1() |,
- extract2 => q| extract2() |,
- extract3 => q| extract3() |,
- extract4 => q| extract4() |,
- };
- timethese( 100, $code );
- #--- Result
- Benchmark: timing 100 iterations of extract1, extract2, extract3, extract4, my_copy...
- extract1: 20 wallclock secs (17.63 usr + 0.87 sys = 18.50 CPU) @ 5.41/s (n=100)
- extract2: 26 wallclock secs (25.50 usr + 0.42 sys = 25.92 CPU) @ 3.86/s (n=100)
- extract3: 14 wallclock secs (13.74 usr + 0.32 sys = 14.06 CPU) @ 7.11/s (n=100)
- extract4: 12 wallclock secs (10.43 usr + 0.34 sys = 10.77 CPU) @ 9.29/s (n=100)
- my_copy: 7 wallclock secs ( 6.75 usr + 0.07 sys = 6.82 CPU) @ 14.66/s (n=100)
复制代码 |
|