1 package tests.jfun.yan.benchmark; 6 7 import java.text.NumberFormat ; 8 9 20 public abstract class Benchmark { 21 private String title; 22 private long loops; 23 private double average; 24 private double speed; 25 private long elapsed; 26 27 public Benchmark(String title, long loops) { 28 this.title = title; 29 this.loops = loops; 30 } 31 32 public long start() { 33 return start(false); 34 } 35 36 public long start(boolean forceRun) { 37 long loop = loops; 38 39 if (!forceRun) { 40 if (System.getProperty("bench") == null) { 41 System.out.println("Benchmark is disabled, to enable it, append \"-Dbench=true\" to jvm startup args"); 42 return 0; 43 } 44 } 45 try { 46 Thread.sleep(100); 47 System.gc(); 48 } catch (Exception e) { 49 } 51 long start = System.currentTimeMillis(); 52 try { 53 for (int i = 0; i < loop; i++) { 54 run(); 55 } 56 } catch (Throwable t) { 57 throw new RuntimeException (t); 58 } 59 long end = System.currentTimeMillis(); 60 elapsed = end - start; 61 average = ((double) elapsed) / ((double) loop); 62 speed = (double) loop / (double) elapsed * (double) 1000; 63 NumberFormat nf = NumberFormat.getNumberInstance(); 64 65 StringBuffer sb = new StringBuffer (); 66 sb.append("Benchmark of [").append(title).append("]\n"); 67 sb.append(" - Loops:\t").append(nf.format(loops)).append("\n"); 68 sb.append(" - Elapsed:\t").append(elapsed).append(" ms\n"); 69 sb.append(" - Average:\t").append(average).append(" ms/call\n"); 70 sb.append(" - Speed:\t").append(nf.format(speed)).append(" calls/scond"); 71 72 System.out.println(sb.toString()); 73 return elapsed; 74 } 75 76 public abstract void run() throws Exception ; 77 78 public double getAverage() { 79 return average; 80 } 81 82 public long getElapsed() { 83 return elapsed; 84 } 85 86 public long getLoops() { 87 return loops; 88 } 89 90 public double getSpeed() { 91 return speed; 92 } 93 94 public String getTitle() { 95 return title; 96 } 97 } 98 | Popular Tags |