%hash = ( 100 => '1', 101 => '23', 102 => '4', ... 200 => '75' ); #### #!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $data = {}; $data->{$_} = rand for (10000 .. 30000); print average($data, 15000, 25000), "\n"; cmpthese(50, { orig => sub { average($data, 15000, 25000) } }); sub average { my ($data, $start_point, $end_point) = @_; my @keys = sort keys %{ $data }; my $start_pos; my $end_pos; for (0 .. $#keys) { $start_pos = $_ if $keys[$_] eq $start_point; $end_pos = $_ if $keys[$_] eq $end_point; } return undef unless defined $start_pos and defined $end_pos; my $count = $end_pos - $start_pos + 1; my $amount; $amount += $data->{$keys[$_]} for ($start_pos .. $end_pos); return $amount / $count; }