Last active
December 11, 2015 21:48
-
-
Save uvtc/4664608 to your computer and use it in GitHub Desktop.
crunch-it: little benchmark in Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Modern::Perl; | |
#use diagnostics; | |
use List::Util qw/max min sum/; | |
# TODO: more of the following code needs to be put into functions | |
if (@ARGV != 1) { | |
say "Please pass exactly one arg: the number of"; | |
say "random strings to be generated for this run."; | |
exit; | |
} | |
my $num_strings_to_generate = $ARGV[0]; | |
my $DEBUG = 0; | |
my @sample_chars = ('a' .. 'l', 0 .. 9); | |
my @random_strings; | |
sub make_random_string { | |
# take $n items from list @a, and join them | |
# together into a string. | |
my ($n, @a) = @_; | |
my $accum = ''; | |
for my $i (1 .. $n) { | |
my $r = $a[ rand(@a) ]; | |
$accum .= $r; | |
} | |
return $accum; | |
} | |
for (1 .. $num_strings_to_generate) { | |
push @random_strings, make_random_string(10, @sample_chars); | |
} | |
if ($DEBUG) { say "DEBUG: random strings: @random_strings"; } | |
my @nums = (); | |
my %num_chars = (); | |
for (3 .. 10) { $num_chars{$_} = 0; } | |
sub show_num_chars { | |
my ($h_ref) = @_; | |
for my $k (sort keys %{$h_ref}) { # sort these an nums, not strs! XXX | |
say " $k: ", ${$h_ref}{$k}; | |
} | |
} | |
for my $s (@random_strings) { | |
if ($s =~ m/([1-9]\d{2,})/) { | |
$num_chars{ length($1) }++; | |
push @nums, $1; | |
} | |
} | |
if ($DEBUG) { say "DEBUG, nums: @nums"; } | |
say "Generated ", scalar(@random_strings), " random strings."; | |
say "Found ", scalar @nums, " numbers."; | |
say "Min: ", min(@nums), '.'; | |
say "Max: ", max(@nums), '.'; | |
say "Distribution:"; | |
show_num_chars(\%num_chars); | |
my @logs = (); | |
for my $n (@nums) { push @logs, log($n); } | |
if ($DEBUG) { say "DEBUG, logs: @logs"; } | |
my $avg = sum(@logs) / @logs; | |
say "Avg of natural logs:", sprintf("%.2f", $avg); | |
say '-' x 42; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment