1 9 10 package org.dom4j.samples.performance; 11 12 18 public class Timer { 19 20 21 protected static boolean VERBOSE = false; 22 23 24 protected static final int DEFAULT_LOOP_COUNT = 40; 25 26 27 private int displayCount = 4; 28 29 30 private int loopCount = DEFAULT_LOOP_COUNT; 31 32 private Task task; 33 34 public Timer() { 35 } 36 37 public Timer(Task task) { 38 this.task = task; 39 } 40 41 47 public void run() throws Exception { 48 Task task = getTask(); 49 int size = getLoopCount(); 50 if (size <= 0 || task == null) { 51 return; 52 } 53 54 long[] times = new long[size]; 55 for (int i = 0; i < size; i++) { 56 long start = System.currentTimeMillis(); 57 58 task.run(); 59 60 long end = System.currentTimeMillis(); 61 times[i] = end - start; 62 } 63 64 printSummary(times); 65 } 66 67 public Task getTask() { 70 return task; 71 } 72 73 public void setTask(Task task) { 74 this.task = task; 75 } 76 77 public int getLoopCount() { 78 return loopCount; 79 } 80 81 public void setLoopCount(int loopCount) { 82 this.loopCount = loopCount; 83 } 84 85 protected void printSummary(long[] times) { 88 println("Performance summary"); 89 90 println("Number of runs: " + loopCount); 91 92 if (VERBOSE || loopCount < displayCount) { 93 displayCount = loopCount; 94 } 95 for (int i = 0; i < displayCount; i++) { 96 println("run: " + i + " took: " + times[i] + " (ms)"); 97 } 98 99 long minimum = times[0]; 100 for (int i = 1; i < loopCount; i++) { 101 long time = times[i]; 102 if (time < minimum) { 103 minimum = time; 104 } 105 } 106 107 println("Minimum time of run : " + minimum + " (ms)"); 108 109 long total = 0; 111 for (int i = 0; i < loopCount; i++) { 112 total += times[i]; 113 } 114 115 double average = total / loopCount; 116 117 println("Average time of run : " + average + " (ms)"); 118 119 if (loopCount == 1) { 120 return; 121 } 122 long total_1 = total - times[0]; 123 average = total_1 / (loopCount - 1); 124 125 println("Average (excluding first run) : " + average + " (ms)"); 126 127 if (loopCount == 2) { 128 return; 129 } 130 long total_2 = total_1 - times[1]; 131 average = total_2 / (loopCount - 2); 132 133 println("Average (excluding first & second run): " + average + " (ms)"); 134 135 println("Total time of run : " + total + " (ms)"); 136 println("Total (excluding first run) : " + total_1 + " (ms)"); 137 println("Total (excluding first & second run) : " + total_2 + " (ms)"); 138 139 return; 140 } 141 142 protected void println(String text) { 143 System.out.println(text); 144 } 145 } 146 147 185 | Popular Tags |