Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program SwapTest;
- {$APPTYPE CONSOLE}
- {$R *.res}
- // Initially from : http://www.delphigroups.info/2/29/2921.html
- uses
- System.Diagnostics;
- procedure SwapPas(var Left, Right: Integer);
- var
- temp: Integer;
- begin
- temp := Left;
- Left := Right;
- Right := temp;
- end;
- procedure SwapXor(var Left, Right: Integer);
- begin
- Left := Left xor Right;
- Right := Right xor Left;
- Left := Left xor Right;
- end;
- procedure SwapAsm(var Left, Right: Integer);
- asm
- {$IFDEF CPUX86}
- xchg ecx, [eax]
- xchg ecx, [edx]
- xchg [eax], ecx
- {$ENDIF}
- {$IFDEF CPUX64}
- xchg eax, [rcx]
- xchg eax, [rdx]
- xchg [rcx], eax
- {$ENDIF}
- end;
- // -----------------------------------------------------------------------
- type
- TGeneric = class
- public
- class procedure Swap<T>(var Left, Right: T); static;
- end;
- class procedure TGeneric.Swap<T>(var Left, Right: T);
- var
- temp: T;
- begin
- temp := Left;
- Left := Right;
- Right := temp;
- end;
- {
- For 32 bit with T = Pointer we have:
- push ebx
- mov ecx,[eax]
- mov ebx,[edx]
- mov [eax],ebx
- mov [edx],ecx
- pop ebx
- ret
- For 64 bit with T = Pointer we have:
- mov rax,[rcx]
- mov r8,[rdx]
- mov [rcx],r8
- mov [rdx],rax
- ret
- }
- // -----------------------------------------------------------------------
- const
- N = 5000;
- var
- i, j: Integer;
- A, B: array [1..5000] of integer;
- //A, B: TArray<Integer>;
- Stopwatch: TStopwatch;
- begin
- //SetLength(A, N);
- //SetLength(B, N);
- for i := Low(A) to High(A) do begin
- A[i] := i;
- B[i] := N-i;
- end;
- //B := Copy(A);
- Stopwatch := TStopwatch.StartNew;
- for j := 1 to 100000 do
- for i := low(A) to high(A) do
- SwapPas(A[i], B[i]);
- Writeln('SwapPas: ', Stopwatch.ElapsedMilliseconds);
- Stopwatch := TStopwatch.StartNew;
- for j := 1 to 100000 do
- for i := low(A) to high(A) do
- TGeneric.Swap(A[i], B[i]);
- Writeln('SwapGen: ', Stopwatch.ElapsedMilliseconds);
- Stopwatch := TStopwatch.StartNew;
- for j := 1 to 100000 do
- for i := low(A) to high(A) do
- SwapXor(A[i], B[i]);
- Writeln('SwapXor: ', Stopwatch.ElapsedMilliseconds);
- Stopwatch := TStopwatch.StartNew;
- for j := 1 to 100000 do
- for i := low(A) to high(A) do
- SwapAsm(A[i], B[i]);
- Writeln('SwapAsm: ', Stopwatch.ElapsedMilliseconds);
- Writeln('**');
- Stopwatch.Stop;
- Readln;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement