Skip to content

Instantly share code, notes, and snippets.

@MattOates
Last active June 25, 2018 17:45
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 MattOates/845874a634f35de74acd6f1a70c51fe0 to your computer and use it in GitHub Desktop.
Save MattOates/845874a634f35de74acd6f1a70c51fe0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
use v6;
use Stats;
#Quick benchmark script for https://www.reddit.com/r/perl6/comments/8tdfvz/handwavy_speed_test/
# $ perl6 annual-rate.p6 --upto=100
# annual-rate-with-helper: ran in 0.0551038961038961 seconds (σ = 0.015335042908917152 seconds)
# Result was 1.3232569411493311
# annual-rate-rat-exp: ran in 0.7545948945615983 seconds (σ = 0.03632803218476478 seconds)
# Result was 1.3232569411482977
# annual-rate-double-exp: ran in 0.00017207147584381207 seconds (σ = 7.260006998518607e-05 seconds)
# Result was 1.3232569411493331
sub bench(Str $name, Int $upto, &code) {
my ($start,$end);
my @times;
for 1..$upto {
$start = now;
code();
$end = now;
@times.push($end-$start);
}
my $sd = sd @times;
my $mu = mean @times;
say "$name: ran in $mu seconds (σ = $sd seconds)";
}
sub annual-rate-with-helper($n) {
annual-rate-helper($n,$n);
}
sub annual-rate-helper($n, $d) {
if ($n == 0) {
return 1;
} else {
return (1 + (.2801 / $d)) * annual-rate-helper($n - 1, $d);
}
}
sub annual-rate-rat-exp($n) {
return (1 + (.2801 / $n)) ** $n;
}
sub annual-rate-double-exp(num64 $n) {
my num64 $rate = 0.2801e0;
my num64 $one = 1.0e0;
#Using the $one here actually gets compiled down to something much better than relying on a 1.0e0 literal
#the reason is this wont be a num64 by default when compiled, the overall time is very close, but the sigma is *much* higher
#this I assume is because the JIT has to work out how to promote the literal to the right native type
return ($one + ($rate / $n)) ** $n;
}
sub MAIN(Int :$upto) {
my $result;
bench 'annual-rate-with-helper', $upto, {
$result = annual-rate-with-helper(10000)
}
say "Result was $result";
bench 'annual-rate-rat-exp', $upto, {
$result = annual-rate-rat-exp(10000)
}
say "Result was $result";
bench 'annual-rate-double-exp', $upto, {
$result = annual-rate-double-exp(10000.0e0)
}
say "Result was $result";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment