use strict;
use Benchmark qw/timethese/;
my $str;
my $index = 82;
# construct a small string
foreach (1..100) { $str .= "Element$_" . ' ' }
timethese(100000, {
'FindNth_Roger' => '&FindNth_Roger',
'FindNth_Zaxo_Array' => '&FindNth_Zaxo_Array',
'FindNth_Zaxo_Split' => '&FindNth_Zaxo_Split',
'FindNth_Ysth' => '&FindNth_Ysth',
'FindNth_Pg' => '&FindNth_Pg',
'FindNth_Grantm' => '&FindNth_Grantm',
'FindNth_Jasper' => '&FindNth_Jasper',
});
sub FindNth_Roger() {
my $nth = @{[$str =~ m/\w+/g]}[$index-1];
}
sub FindNth_Zaxo_Array() {
my $nth = ($str =~ m/\w+/g)[$index-1];
}
sub FindNth_Zaxo_Split() {
my $nth = (split ' ', $str)[$index-1];
}
sub FindNth_Ysth() {
my $nth = [$str =~ m/\w+/g]->[$index-1];
}
sub FindNth_Pg() {
my ($nth) = ($str =~ m/(\w+\s*){$index}/);
}
sub FindNth_Grantm() {
my $idx = $index - 1;
my ($nth) = $str =~ /(?:\w+\W+){$idx}(\w+)/;
}
sub FindNth_Jasper() {
my $nth;
my %h;
for ($str=~/.?/g) {
$h{space} += !/\S/;
$nth .= $_ if $h{space} == $index-1 && /\S/ .. !/\S/
}
}
####
Benchmark: timing 100000 iterations of FindNth_Grantm, FindNth_Jasper,
FindNth_Pg, FindNth_Roger, FindNth_Ysth, FindNth_Zaxo_Array,
FindNth_Zaxo_Split...
FindNth_Grantm: 3 wallclock secs (3.50 usr + 0.00 sys = 3.50 CPU)
@ 28571.43/s
FindNth_Jasper: 379 wallclock secs (376.66 usr + 0.06 sys = 376.72 CPU)
@ 265.45/s
FindNth_Pg: 4 wallclock secs (3.91 usr + 0.00 sys = 3.91 CPU)
@ 25595.09/s
FindNth_Roger: 21 wallclock secs (21.03 usr + 0.00 sys = 21.03 CPU)
@ 4754.66/s
FindNth_Ysth: 21 wallclock secs (20.95 usr + 0.00 sys = 20.95 CPU)
@ 4772.36/s
FindNth_Zaxo_Array: 19 wallclock secs (18.53 usr + 0.00 sys = 18.53 CPU)
@ 5396.36/s
FindNth_Zaxo_Split: 14 wallclock secs (14.51 usr + 0.02 sys = 14.53 CPU)
@ 6882.31/s
####
# Pg's approach
my ($nth) = ($str =~ m/(\w+\s*){$index}/);
# Grantm's approach
my $idx = $index - 1;
my ($nth) = $str =~ /(?:\w+\W+){$idx}(\w+)/;