Advertisement
Guest User

Flippable benchmark

a guest
Oct 17th, 2013
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. /*  0% Scenario{vm=java, trial=0, benchmark=FlipOne} 12.23 ns; ?=0.12 ns @ 6 trials
  2.  * 50% Scenario{vm=java, trial=0, benchmark=FlipTwo} 18.89 ns; ?=0.43 ns @ 10 trials
  3.  
  4.  * benchmark   ns linear runtime
  5.  *   FlipOne 12.2 ===================
  6.  *   FlipTwo 18.9 ==============================
  7.  
  8.  * vm: java
  9.  * trial: 0
  10.  */
  11.  
  12. import java.util.Random;
  13.  
  14. import com.google.caliper.Runner;
  15. import com.google.caliper.SimpleBenchmark;
  16.  
  17. public class FlipTest {
  18.     public static enum FlipOne {
  19.         A, B, Z, Y;
  20.  
  21.         static {
  22.             A.opposite = Z;
  23.             B.opposite = Y;
  24.             Y.opposite = B;
  25.             Z.opposite = A;
  26.         }
  27.  
  28.         public FlipOne flip() {
  29.             return opposite;
  30.         }
  31.  
  32.         private FlipOne opposite;
  33.     }
  34.  
  35.     public static enum FlipTwo {
  36.         A ("Z"), B ("Y"), Y ("B"), Z ("A");
  37.  
  38.         private final String opposite;
  39.  
  40.         private FlipTwo(String opposite) {
  41.             this.opposite = opposite;
  42.         }
  43.  
  44.         public FlipTwo flip() {
  45.             return valueOf(opposite);
  46.         }
  47.     }
  48.  
  49.     public static class TestBenchmark extends SimpleBenchmark {
  50.         private Random r;
  51.         private int[] counters;
  52.  
  53.         @Override
  54.         protected void setUp() throws Exception {
  55.             r = new Random();
  56.             counters = new int[4];
  57.         }
  58.  
  59.         public int timeFlipOne(int reps) {
  60.             for (int i = 0; i < reps; i++) {
  61.                 FlipOne randomFlip = FlipOne.values()[r.nextInt(4)];
  62.                 counters[randomFlip.flip().ordinal()]++;
  63.             }
  64.             return counters[0] * counters[1] * counters[2] * counters[3];
  65.         }
  66.  
  67.         public int timeFlipTwo(int reps) {
  68.             for (int i = 0; i < reps; i++) {
  69.                 FlipTwo randomFlip = FlipTwo.values()[r.nextInt(4)];
  70.                 counters[randomFlip.flip().ordinal()]++;
  71.             }
  72.             return counters[0] * counters[1] * counters[2] * counters[3];          
  73.         }
  74.     }
  75.  
  76.     public static void main(String[] args) {
  77.         Runner.main(TestBenchmark.class, new String[0]);
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement