记录几个测试算法性能的工具类,方便以后测试算法.
Stopwatch类:可以得到算法的执行时间(单位:s,小数点后3位)
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: }
例如:测试选择排序和插入排序的性能
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为模板,比较不同算法之间的差异.
转载于:https://blog.51cto.com/youngcold/1112813