Skip to content

Instantly share code, notes, and snippets.

@Gregoor
Created June 10, 2014 14:35
Show Gist options
  • Save Gregoor/547c0451c4fa527dd85c to your computer and use it in GitHub Desktop.
Save Gregoor/547c0451c4fa527dd85c to your computer and use it in GitHub Desktop.
import 'package:benchmark_harness/benchmark_harness.dart';
import 'dart:math';
void main() {
var keyFn = (n) {
var sum = n % 9;
if (sum == 0 && n > 0) sum = 9;
return sum;
},
compFn = (n1, n2) => keyFn(n1).compareTo(keyFn(n2));
Random rand = new Random();
double totalKeySortScore = .0,
totalCompSortScore = .0;
for (int i = 0; i < 10; i++) {
List list = new List.generate(1000, (_) => rand.nextInt(1000000), growable: false);
print("Run $i with list: $list");
var keySortBench = new KeySortBenchmark(new List.from(list, growable: false), keyFn),
compSortBench = new CompSortBenchmark(new List.from(list, growable: false), compFn);
double keySortScore = keySortBench.measure(),
compSortScore = compSortBench.measure();
totalKeySortScore += keySortScore;
totalCompSortScore += compSortScore;
print("KeySort scored $keySortScore. Result: ${keySortBench.list}");
print("CompSort scored $compSortScore. Result: ${compSortBench.list}");
print("\n");
}
print("Total scores: KeySort - $totalKeySortScore | CompSort - $totalCompSortScore");
}
class KeySortBenchmark extends BenchmarkBase {
List list;
var fn;
KeySortBenchmark(this.list, this.fn) : super('KeySortBenchmark');
run() {
new KeySorter(list).sort(fn);
}
}
class CompSortBenchmark extends BenchmarkBase {
List list;
var fn;
CompSortBenchmark(this.list, this.fn) : super('CompSortBenchmark');
run() {
list.sort(fn);
}
}
class KeySorter<V, K extends Comparable> {
List<V> list;
KeySorter(this.list);
List<V> sort(K keyFn(V)) {
Map<V, K> keys = {};
list.sort((e1, e2) {
var e1Key = keys.putIfAbsent(e1, () => keyFn(e1)),
e2Key = keys.putIfAbsent(e2, () => keyFn(e2));
return e1Key.compareTo(e2Key);
});
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment