Created
August 17, 2011 18:22
-
-
Save paradigmatic/1152232 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
package org.example | |
import annotation.tailrec | |
import com.google.caliper.Param | |
class CaseOrder extends SimpleScalaBenchmark { | |
abstract class Expr | |
case class Var(name: String) extends Expr | |
case class Number(num: Double) extends Expr | |
case class UnOp(operator: String, arg: Expr) extends Expr | |
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr | |
object ExprFirst { | |
def simplify(expr: Expr): Expr = expr match { | |
// Some basic simplification rules... | |
case UnOp("-", UnOp("-", e)) => simplify(e) // Double negation | |
case BinOp("+", e, Number(0)) => simplify(e) // Adding zero | |
case BinOp("-", e, Number(0)) => simplify(e) // Subtracting zero | |
case BinOp("*", e, Number(1)) => simplify(e) // Multiplying by one | |
case BinOp("*", e, Number(0)) => Number(0) // Multiplying by zero | |
case _ => expr // Default, could not simplify given above rules | |
} | |
} | |
object ExprLast { | |
def simplify(expr: Expr): Expr = expr match { | |
// Some basic simplification rules... | |
case BinOp("+", e, Number(0)) => simplify(e) // Adding zero | |
case BinOp("-", e, Number(0)) => simplify(e) // Subtracting zero | |
case BinOp("*", e, Number(1)) => simplify(e) // Multiplying by one | |
case BinOp("*", e, Number(0)) => Number(0) // Multiplying by zero | |
case UnOp("-", UnOp("-", e)) => simplify(e) // Double negation | |
case _ => expr // Default, could not simplify given above rules | |
} | |
} | |
@tailrec | |
private def buildInput( start: Expr, n: Int ): Expr = | |
if( n == 0 ) start | |
else buildInput( UnOp("-", start ), n-1) | |
val input = buildInput( Var("x"), 100000 ) | |
def timeForFirst( reps: Int ) = repeat(reps) { | |
ExprFirst.simplify( input ) | |
} | |
def timeForLast( reps: Int ) = repeat(reps) { | |
ExprLast.simplify( input ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment