Last active
August 29, 2015 14:08
-
-
Save dagolden/80420895f0f517838072 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
use strict; | |
use warnings; | |
use Time::HiRes qw/gettimeofday tv_interval/; | |
use List::Util qw/sum0/; | |
use constant { | |
ADD => 0, | |
SUBSTRACT => 1, | |
MULTIPLY => 2, | |
DEVIDE => 3, | |
SUM => 4 | |
}; | |
sub evaluate_ast { | |
my $ast = shift; | |
my ($oper, @args) = @$ast; | |
my @evaluated_args = map { ref eq 'ARRAY' ? evaluate_ast($_) : $_ } @args; | |
if ( $oper == ADD ) { | |
return $evaluated_args[0] + $evaluated_args[1]; | |
} | |
elsif ( $oper == SUBSTRACT ) { | |
return $evaluated_args[0] - $evaluated_args[1]; | |
} | |
elsif ( $oper == MULTIPLY ) { | |
return $evaluated_args[0] * $evaluated_args[1]; | |
} | |
elsif ( $oper == DEVIDE ) { | |
return $evaluated_args[0] / $evaluated_args[1]; | |
} | |
elsif ( $oper == SUM ) { | |
return sum0(@evaluated_args); | |
} | |
} | |
sub time_ast { | |
my $ast = shift; | |
my $t0 = [gettimeofday]; | |
my $iterations = 100_000; | |
my $sum = 0; | |
for (1..$iterations) { | |
$sum += evaluate_ast($ast); | |
} | |
my $compute_time = tv_interval($t0); | |
print "COMPUTED [$iterations] ITERATIONS IN [$compute_time] SECONDS\n"; | |
die "WRONG SUM $sum" if abs( $sum - 3900000) > 0.001; # ensure that code was executed | |
} | |
my $ast = [SUM, | |
[ SUBSTRACT,[ADD,[DEVIDE,[MULTIPLY,10,20],30],40],50], | |
[ SUBSTRACT,[ADD,[DEVIDE,[MULTIPLY,20,30],40],50],60], | |
[ SUBSTRACT,[ADD,[DEVIDE,[MULTIPLY,30,40],50],60],70], | |
[ SUBSTRACT,[ADD,[DEVIDE,[MULTIPLY,40,50],60],70],80] | |
]; | |
time_ast($ast); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment