Skip to content

Instantly share code, notes, and snippets.

@paveljurca
Last active August 29, 2015 14:17
Show Gist options
  • Save paveljurca/8ed9a9c777c31eb3d0be to your computer and use it in GitHub Desktop.
Save paveljurca/8ed9a9c777c31eb3d0be to your computer and use it in GitHub Desktop.
stopwatch test on the particular methods
#!/usr/bin/perl
use strict;
use warnings;
use Time::HiRes qw/time/;
use List::Util qw/reduce/;
###
# finding the max value and its key
# in an associative array
###
sub get_max_value_key {
my %hash_args = @_;
my $max_value_key =
(sort {$hash_args{$b} <=> $hash_args{$a}} keys %hash_args)[0];
return $max_value_key;
}
sub get_max_value_key_2 {
my %hash_args = @_;
my($max,$key) = 0;
for my $k (keys %hash_args) {
my $v = $hash_args{$k};
($max = $v, $key = $k) if $v >= $max;
}
return $key;
}
# yet another way / List::Util
# performance ~ identical with get_max_value_key_2
sub get_max_value_reduce {
my %h = @_;
return reduce
{ $h{$a} > $h{$b} ? $a : $b }
keys %h;
}
## STOPWATCHing ##
sub compare_subs {
my(%hash,$start,$end,@t) = @_;
$start = time();
get_max_value_key(%hash);
$end = time();
push @t, $end - $start;
$start = time();
get_max_value_key_2(%hash);
$end = time();
push @t, $end - $start;
return \@t;
}
sub build_hash {
my %h;
$h{$_} = int(rand(100)) for (1..shift);
return \%h;
}
## TIME efficiency ##
# get_max_value_key
# VS
# get_max_value_key_2
my %results;
for my $size ((10,1_000,10_000,100_000)) {
#mean
my($_sub1,$_sub2);
print ">> $size keys <<\n";
for my $run (1..9) {
my $t_ref = compare_subs(%{build_hash($size)});
$_sub1 += $t_ref->[0];
$_sub2 += $t_ref->[1];
print "[ run #$run ]\n";
}
$_sub1 /= 9;
$_sub2 /= 9;
#miliseconds
$results{$size} =
sprintf("%27f ms%27f ms", $_sub1*1000, $_sub2*1000);
}
## OUTPUT ##
# results
printf(
"%s%15s%30s%30s\n\n",
"\n=== RESULTS ===\n","",
"get_max_value_key",
"get_max_value_key_2"
);
printf(
"%15s%s\n",
"$_ keys:",
$results{$_}
) for (sort {$a<=>$b} keys %results);
=== RESULTS ===
get_max_value_key get_max_value_key_2
10 keys: 0.022888 ms 0.012822 ms
1000 keys: 2.931780 ms 0.696765 ms
10000 keys: 39.346827 ms 7.580095 ms
100000 keys: 577.573220 ms 90.458022 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment