Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.micro.bench;
- import javassist.ClassPool;
- import javassist.CtClass;
- import javassist.CtNewMethod;
- interface Evaluator {
- public double eval(double x);
- }
- abstract class Fight {
- private int steps;
- private int loops;
- public Fight(int loops, int steps) {
- this.loops = loops;
- this.steps = steps;
- }
- public abstract Object step(Timer timer);
- public void loop(Timer timer) {
- for (int j = 0; j < steps; ++j) {
- step(timer);
- }
- }
- public void fight() {
- Timer statistics = new Timer();
- for (int i = 0; i < loops; i++) {
- loop(statistics);
- statistics.flush();
- System.out.println(statistics);
- }
- }
- }
- public class Evaluation extends Fight {
- private static final int MAX = 1000000;
- private Evaluator runtime;
- private Evaluator compileTime;
- public Evaluation(int loops, int steps) {
- super(loops, steps);
- init();
- }
- public void init() {
- try {
- ClassPool pool = ClassPool.getDefault();
- CtClass evalClass = pool.makeClass("Formula");
- evalClass.setInterfaces(
- new CtClass[]{
- pool.makeClass("com.micro.bench.Evaluator")
- });
- String expession = "x * x + x / 2";
- evalClass.addMethod(
- CtNewMethod.make(
- "public double eval (double x) { return (" + expession + ") ; }",
- evalClass));
- Class clazz = evalClass.toClass();
- runtime = (Evaluator) clazz.newInstance();
- } catch (Exception e) {
- e.printStackTrace();
- }
- compileTime = new Evaluator() {
- public double eval(double x) {
- return x * x + x / 2;
- }
- };
- }
- public Object step(Timer timer) {
- timer.start("runtime calc");
- double result = 0;
- for (int i1 = 0; i1 < MAX; i1++) {
- result += runtime.eval(i1);
- }
- timer.stop();
- double i = result;
- timer.start("compile-time calc");
- double result11 = 0;
- for (int i1 = 0; i1 < MAX; i1++) {
- result11 += compileTime.eval(i1);
- }
- timer.stop();
- return i + result11;
- }
- public static void main(String[] args) throws Exception {
- new Evaluation(20, 100).fight();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement