#!/usr/bin/perl use strict; use warnings; use List::Util qw/first reduce/; use Benchmark qw/ cmpthese /; my $file = 'bench_reduce.txt'; open my $fh, '<', $file or die $!; my @data = <$fh>; seek $fh, 0, 0; my @chunks; { local $/ = ""; @chunks = <$fh>; } my $cache = sub { my %c; # cache my $max = reduce {($c{$a}//=f_32($a)) > ($c{$b}//=f_32($b)) ? $a : $b} @chunks; ($max) = $max =~ /\A(.+)/; #print $max; }; my $reduce = sub { my $max = reduce {f_32($a) > f_32($b) ? $a : $b} @chunks; ($max) = $max =~ /\A(.+)/; #print $max; }; sub f_32 { $_[0] =~ /^32 (\S+)/m; return $1; } my $tshiono = sub { my ($maxline, $firstline); my $max = 0; my $target = 32; for (@data) { next unless /\S/; chop; # also tested with chomp and with neither chop nor chomp if (/^\d+:/) { # treat the 1st line $firstline = $_; # keep the 1st line } elsif (/^(\d+) +([\d.]+)/) { # treat other lines in the block if ($1 == $target && $2 > $max) { $max = $2; # update the highest value $maxline = $firstline; # and the 1st line of the block } } } }; my $_7stud = sub { my %results; for my $block (@chunks) { my @lines = split /\n/, $block; my $line32 = first {/^32/} @lines; (undef, my $ranking_num) = split ' ', $line32; $results{$ranking_num} = $lines[0]; } my @sorted_nums = sort{$a <=> $b} keys %results; my $biggest_num = $sorted_nums[-1]; }; cmpthese (-1, { w_o_cache => $reduce, w_cache => $cache, tshiono => $tshiono, '7stud' => $_7stud }); __END__ C:\Old_Data\perlp>perl test2.pl (with chop tshiono) Rate 7stud w_o_cache w_cache tshiono 7stud 200/s -- -37% -45% -92% w_o_cache 320/s 60% -- -12% -87% w_cache 364/s 82% 14% -- -86% tshiono 2557/s 1180% 700% 602% -- C:\Old_Data\perlp>perl test2.pl (with chomp tshiono) Rate tshiono 7stud w_o_cache w_cache tshiono 160/s -- -19% -50% -57% 7stud 197/s 23% -- -38% -47% w_o_cache 318/s 98% 61% -- -15% w_cache 373/s 133% 90% 17% -- C:\Old_Data\perlp>perl test2.pl (w/o chop or chomp tshiono) Rate tshiono 7stud w_o_cache w_cache tshiono 177/s -- -13% -45% -52% 7stud 202/s 15% -- -37% -45% w_o_cache 321/s 82% 59% -- -13% w_cache 370/s 109% 83% 15% --