Skip to content

Instantly share code, notes, and snippets.

@mjsr
Created May 28, 2014 10:30
Show Gist options
  • Save mjsr/0bb73ca0afd000a2875e to your computer and use it in GitHub Desktop.
Save mjsr/0bb73ca0afd000a2875e to your computer and use it in GitHub Desktop.
Benchmark subroutine argument strategies
#!perl
# source: http://www.perlmonks.org/?node_id=575918
use warnings;
use strict;
use Benchmark;
timethese(1_000_000, {
'use_shift' => sub { sub_with_shift(0..9) },
'use_list' => sub { sub_with_list(0..9) },
'use_direct' => sub { sub_with_direct(0..9) },
});
sub sub_with_shift
{
my $sum = 0;
while (@_)
{
$sum += shift;
}
$sum;
}
sub sub_with_list
{
my(@a)=@_;
my $sum = 0;
$sum += $_
for @a;
$sum;
}
sub sub_with_direct
{
my $sum = 0;
$sum += $_
for @_;
$sum;
}
@mjsr
Copy link
Author

mjsr commented May 28, 2014

Results on my desktop:

$ perl benchmark_sub_args.pl 
Benchmark: timing 1000000 iterations of use_direct, use_list, use_shift...
use_direct:  0 wallclock secs ( 0.60 usr +  0.00 sys =  0.60 CPU) @ 1666666.67/s (n=1000000)
  use_list:  1 wallclock secs ( 0.93 usr +  0.00 sys =  0.93 CPU) @ 1075268.82/s (n=1000000)
 use_shift: -1 wallclock secs ( 0.63 usr +  0.00 sys =  0.63 CPU) @ 1587301.59/s (n=1000000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment