tqsort_killer.pp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. {$mode objfpc} {$h+} {$typedaddress on} {$modeswitch advancedrecords} {$coperators on} {$modeswitch anonymousfunctions}
  2. {$modeswitch duplicatelocals}
  3. uses
  4. SysUtils, Generics.Collections, Generics.Defaults;
  5. var
  6. anythingWrong: boolean = false;
  7. generic procedure Swap<Ty>(var a, b: Ty);
  8. var
  9. temp: Ty;
  10. begin
  11. temp := a; a := b; b := temp;
  12. end;
  13. type
  14. generic TTracingComparer<Ty> = class(specialize TComparer<Ty>)
  15. orig: specialize IComparer<Ty>;
  16. count: uint64;
  17. constructor Create(const orig: specialize IComparer<Ty>);
  18. function Compare(const a, b: Ty): integer; override;
  19. end;
  20. constructor TTracingComparer.Create(const orig: specialize IComparer<Ty>);
  21. begin
  22. inherited Create;
  23. self.orig := orig;
  24. end;
  25. function TTracingComparer.Compare(const a, b: Ty): integer;
  26. begin
  27. result := orig.Compare(a, b);
  28. count += 1;
  29. end;
  30. type
  31. // https://igoro.com/archive/quicksort-killer/
  32. // Will work against wide range of qsort implementations.
  33. TQSortKillerComparer = class(specialize TComparer<SizeInt>)
  34. keys: array of int32; { TDictionary is a lot slower... }
  35. candidate, nKeys: int32;
  36. constructor Create(arrayLen: SizeInt);
  37. function Compare(const a, b: SizeInt): integer; override;
  38. end;
  39. constructor TQSortKillerComparer.Create(arrayLen: SizeInt);
  40. begin
  41. inherited Create;
  42. SetLength(keys, arrayLen);
  43. FillChar(pInt32(keys)^, length(keys) * sizeof(keys[0]), byte(-1));
  44. end;
  45. function TQSortKillerComparer.Compare(const a, b: SizeInt): integer;
  46. begin
  47. if keys[a] and keys[b] < 0 then
  48. begin
  49. if a = candidate then keys[a] := nKeys else keys[b] := nKeys;
  50. nKeys += 1;
  51. end;
  52. if keys[a] < 0 then begin candidate := a; exit(1); end;
  53. if keys[b] < 0 then begin candidate := b; exit(-1); end;
  54. result := keys[a] - keys[b];
  55. end;
  56. type
  57. generic SortBenchmark<Ty> = record
  58. type
  59. CreateProc = function(id: SizeUint): Ty;
  60. TyArray = array of Ty;
  61. class procedure Run(create: CreateProc; const tyPlural: string; lenMul: double); static;
  62. class procedure BenchSort(const src, ref: array of Ty; var prevComparisons: uint64); static;
  63. // 'ref' must be sorted and contain no duplicates.
  64. class function BuildQSortKiller(const ref: array of Ty): TyArray; static;
  65. end;
  66. class procedure SortBenchmark.Run(create: CreateProc; const tyPlural: string; lenMul: double);
  67. type
  68. OrderEnum = (RandomOrder, QSortKillerOrder);
  69. const
  70. OrderNames: array[OrderEnum] of string = ('random', 'QSort killer');
  71. var
  72. ref, src: TyArray;
  73. i, lenBase, len: SizeInt;
  74. cmp: specialize IComparer<Ty>;
  75. srcOrder: OrderEnum;
  76. msg: string;
  77. prevComparisons: uint64;
  78. begin
  79. writeln('--- ', tyPlural, ' ---', LineEnding);
  80. for srcOrder in OrderEnum do
  81. begin
  82. writeln('Order: ', OrderNames[srcOrder], '.');
  83. prevComparisons := uint64(-1);
  84. for lenBase in specialize TArray<SizeInt>.Create(10 * 1000, 20 * 1000, 40 * 1000) do
  85. begin
  86. len := round(lenMul * lenBase);
  87. SetLength((@ref)^, len);
  88. cmp := specialize TComparer<Ty>.Default;
  89. for i := 0 to len - 1 do
  90. begin
  91. ref[i] := create(i);
  92. if (i > 0) and (cmp.Compare(ref[i - 1], ref[i]) >= 0) then
  93. begin
  94. writeln('''create'' callback must return ', tyPlural, ' in strictly ascending order.');
  95. anythingWrong := true;
  96. exit;
  97. end;
  98. end;
  99. case srcOrder of
  100. RandomOrder:
  101. begin
  102. RandSeed := 1;
  103. src := Copy(ref);
  104. for i := len - 1 downto 1 do
  105. specialize Swap<Ty>(src[i], src[random(int64(i))]);
  106. end;
  107. QSortKillerOrder:
  108. src := BuildQSortKiller(ref);
  109. end;
  110. WriteStr(msg, 'n = ', len, ': ');
  111. write(msg.PadRight(12));
  112. BenchSort(src, ref, prevComparisons);
  113. end;
  114. writeln;
  115. end;
  116. end;
  117. class function SortBenchmark.BuildQSortKiller(const ref: array of Ty): TyArray;
  118. var
  119. ris: array of SizeInt;
  120. i: SizeInt;
  121. cmpRef: specialize IComparer<SizeInt>;
  122. begin
  123. SetLength((@ris)^, length(ref));
  124. for i := 0 to High(ris) do ris[i] := i;
  125. cmpRef := TQSortKillerComparer.Create(length(ref));
  126. specialize TArrayHelper<SizeInt>.Sort(ris, cmpRef);
  127. SetLength((@result)^, length(ref));
  128. for i := 0 to High(result) do result[ris[i]] := ref[i];
  129. end;
  130. class procedure SortBenchmark.BenchSort(const src, ref: array of Ty; var prevComparisons: uint64);
  131. var
  132. arr: TyArray;
  133. i: SizeInt;
  134. cmp: specialize TTracingComparer<Ty>;
  135. cmpRef: specialize IComparer<Ty>;
  136. prevCount: uint64;
  137. begin
  138. cmp := specialize TTracingComparer<Ty>.Create(specialize TComparer<Ty>.Default);
  139. cmpRef := cmp;
  140. arr := Copy(src);
  141. specialize TArrayHelper<Ty>.Sort(arr, cmpRef);
  142. prevCount := prevComparisons;
  143. prevComparisons := cmp.count;
  144. write(cmp.count, ' comparisons');
  145. if prevCount <> uint64(-1) then write(' (', cmp.count / prevCount:0:1, 'x from previous)');
  146. for i := 0 to High(ref) do
  147. if arr[i] <> ref[i] then
  148. begin
  149. writeln(', FAIL @ ', i, ' / ', length(ref));
  150. anythingWrong := true;
  151. exit;
  152. end;
  153. if (prevCount <> uint64(-1)) and (cmp.count > 2 * prevCount + prevCount div 2 + 5 * length(src) + 1000) then
  154. begin
  155. writeln(', potentially bad sorting algorithm behaviour');
  156. anythingWrong := true;
  157. exit;
  158. end;
  159. writeln(', OK');
  160. end;
  161. begin
  162. specialize SortBenchmark<string>.Run(
  163. function(id: SizeUint): string
  164. begin
  165. SetLength((@result)^, 5);
  166. result[5] := char(ord('A') + id mod 26); id := id div 26;
  167. result[4] := char(ord('A') + id mod 26); id := id div 26;
  168. result[3] := char(ord('A') + id mod 26); id := id div 26;
  169. result[2] := char(ord('A') + id mod 26); id := id div 26;
  170. result[1] := char(ord('A') + id mod 26);
  171. end, 'strings', 0.15);
  172. specialize SortBenchmark<single>.Run(
  173. function(id: SizeUint): single
  174. begin
  175. result := -1000 + id / 1000;
  176. end, 'float32''s', 1.0);
  177. if anythingWrong then
  178. begin
  179. writeln('Something was wrong, see above.');
  180. halt(2);
  181. end;
  182. end.