記錄幾個測試算法性能的工具類,方便之後測試算法.算法
Stopwatch類:能夠獲得算法的執行時間(單位:s,小數點後3位)app
1: public class Stopwatch {2: private long start;3:
4: public Stopwatch() {5: start = System.currentTimeMillis();
6: }
7:
8: public double elapsedTime(){9: long now = System.currentTimeMillis();10: return (now - start) / 1000.0;11: }
12: }
具體使用方法:1: public static void main(String[] args) {2: Stopwatch timer = new Stopwatch();3: /*調用某個算法*/4: double spend = timer.elapsedTime();5: /*spend就是調用的算法消耗的時間*/6: }
例如:測試選擇排序和插入排序的性能dom
1: public class SortCompare {2: public static double time(String alg,Comparable[] a){3: Stopwatch timer = new Stopwatch();4:
5: if("Insert".equals(alg) || "Insertion".equals(alg))6: new Insertion().sort(a);7: else if("Select".equals(alg) || "Selection".equals(alg))8: new Selection().sort(a);9: /*此處還能夠添加其餘的排序算法*/10:
11: return timer.elapsedTime();12: }
13:
14: public static double timeRandomInput(String alg,int times,int length){15: double total = 0.0;16: Double[] a = new Double[length];17: for(int i = 0;i<times;i++){18: for(int j = 0;j<length;j++)19: a[j] = StdRandom.uniform();
20: total += time(alg, a);
21: }
22: return total;23: }
24:
25: public static void main(String[] args) {26: String alg1 = args[0];
27: String alg2 = args[1];
28: int times = Integer.parseInt(args[2]);29: int length = Integer.parseInt(args[3]);30: double t1 = timeRandomInput(alg1, times, length);31: double t2 = timeRandomInput(alg2, times, length);32: StdOut.printf("For %d randomDoubles \n %s is ", length,alg1);33: StdOut.printf("%.1f times faster than %s\n", t2/t1,alg2);34: }
35: }
測試結果能夠看出結果大體在1~3之間….
總結: 在測試或者比較算法的性能時,能夠以SortCompare爲模板,比較不一樣算法之間的差別.