Skip to content

Instantly share code, notes, and snippets.

@briandfoy
Created September 22, 2014 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandfoy/5373861e3a7e598a5bc1 to your computer and use it in GitHub Desktop.
Save briandfoy/5373861e3a7e598a5bc1 to your computer and use it in GitHub Desktop.
A benchmark to find the first problem in a list
#!/usr/bin/perl
# http://blogs.perl.org/users/jt_smith/2014/09/logically-and-yourself.html
use strict;
use Ouch;
use Benchmark qw(:all);
use List::MoreUtils qw(any);
use v5.10;
my @tests = (
[ '0 first, 100 elements' => [ 0, (1) x 99 ] ],
[ '0 last, 100 elements' => [ (1) x 99, 0 ] ],
[ '0 middle, 100 elements' => [ (1) x 49, '0', (1) x 50 ] ],
[ '0 first, 1,000 elements' => [ 0, (1) x 999 ] ],
[ '0 last, 1,000 elements' => [ (1) x 999, 0 ] ],
[ '0 middle, 1,000 elements' => [ (1) x 499, '0', (1) x 500 ] ],
);
foreach my $test ( @tests ) {
my( $label, $list ) = @$test;
my @list = @$list;
say '-' x 73;
say "Testing $label";
timethese( 1_000, {
'&&=' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
$is_proofed &&= eval { $x ? 1 : ouch(500, 'bad stuff') };
}
},
'$@' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
eval { $x ? 1 : ouch(500, 'bad stuff') };
if ($@) {
$is_proofed = 0;
}
}
},
'$@-last' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
eval { $x ? 1 : ouch(500, 'bad stuff') };
if ($@) {
$is_proofed = 0;
last;
}
}
},
'foreach-eval' => sub {
my $is_proofed = 1;
foreach my $x (@list) {
eval { $x ? 1 : ouch(500, 'bad stuff') };
}
},
'ouch' => sub {
eval { ouch(500, 'bad stuff') };
},
'any' => sub {
my $is_proofed = 1;
my $is_proofed = any {
! defined eval { $_ ? 1 : ouch(500, 'bad stuff') }
} @list;
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment