Last active
March 2, 2020 14:16
-
-
Save synopse/02eb142d35cb44126aed9fd3200a76d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type | |
| ToolsThread = class(TThread) | |
| public | |
| tab : TRawUTF8DynArray; | |
| constructor Create; reintroduce; | |
| procedure Execute; override; | |
| procedure QuickSort(iLo, iHi: Integer); | |
| end; | |
| procedure ToolsThread.QuickSort(iLo, iHi: Integer); | |
| var | |
| Lo, Hi: Longint; | |
| Pivot: Pointer; | |
| T: Pointer; | |
| begin | |
| Lo := iLo; | |
| Hi := iHi; | |
| repeat | |
| Pivot := pointer(tab[(Lo + Hi) shr 1]); // shr 1 is slightly faster than div 2; | |
| while tab[Lo] < RawUTF8(Pivot) do Inc(Lo); | |
| while tab[Hi] > RawUTF8(Pivot) do Dec(Hi); | |
| if Lo <= Hi then | |
| begin | |
| T := pointer(tab[Lo]); | |
| pointer(tab[Lo]) := pointer(tab[Hi]); | |
| pointer(tab[Hi]) := T; | |
| Inc(Lo) ; | |
| Dec(Hi) ; | |
| end; | |
| until Lo > Hi; | |
| if Hi > iLo then QuickSort(iLo, Hi) ; | |
| if Lo < iHi then QuickSort(Lo, iHi) ; | |
| end; | |
| constructor ToolsThread.Create(); | |
| var tmp1: integer; | |
| begin | |
| inherited Create(true); | |
| SetLength(tab, 10000000); | |
| for tmp1:= 0 to high(tab) do | |
| tab[tmp1] := ToUTF8(Random(high(integer))); | |
| end; | |
| procedure ToolsThread.Execute(); | |
| begin | |
| QuickSort(0,high(tab)); | |
| end; | |
| Procedure Main; | |
| var | |
| Th1, Th2, Th3, Th4: ToolsThread; | |
| timer: TPrecisionTimer; | |
| begin | |
| AllocConsole; | |
| write('Fill'); | |
| timer.Start; | |
| Th1 := ToolsThread.Create(); | |
| Th2 := ToolsThread.Create(); | |
| Th3 := ToolsThread.Create(); | |
| Th4 := ToolsThread.Create(); | |
| writeln(' done in ',timer.Stop); | |
| write('Sort'); | |
| timer.Start; | |
| Th1.Resume; | |
| Th2.Resume; | |
| Th3.Resume; | |
| Th4.Resume; | |
| th1.WaitFor; | |
| th2.WaitFor; | |
| th3.WaitFor; | |
| th4.WaitFor; | |
| writeln(' done in ',timer.Stop); | |
| readln; | |
| end; | |
| { output: | |
| Fill done in 3.25s | |
| Sort done in 24.11s | |
| with one core used during Fill/Create - as expected | |
| with all cores used during Sort/Execute - as expected | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment