问题描述
我使用以下函数交换(无符号)64位整数值:
function Swap64(I: Int64): Int64;
begin
Int64Rec(Result).Bytes[0] := Int64Rec(I).Bytes[7];
Int64Rec(Result).Bytes[1] := Int64Rec(I).Bytes[6];
Int64Rec(Result).Bytes[2] := Int64Rec(I).Bytes[5];
Int64Rec(Result).Bytes[3] := Int64Rec(I).Bytes[4];
Int64Rec(Result).Bytes[4] := Int64Rec(I).Bytes[3];
Int64Rec(Result).Bytes[5] := Int64Rec(I).Bytes[2];
Int64Rec(Result).Bytes[6] := Int64Rec(I).Bytes[1];
Int64Rec(Result).Bytes[7] := Int64Rec(I).Bytes[0];
end;
如何在ASM中执行相同的操作以使其更快?
推荐答案
可以使用bswap
指令交换字节。对于32位代码,您需要一次交换32位字节,bswap
有两种用法。对于64位代码,您可以直接在64位寄存器上操作,并且一次使用bswap
交换所有8个字节。
以下是32位和64位目标的函数:
function ByteSwap64(Value: Int64): Int64;
asm
{$IF Defined(CPUX86)}
mov edx, [ebp+$08]
mov eax, [ebp+$0c]
bswap edx
bswap eax
{$ELSEIF Defined(CPUX64)}
mov rax, rcx
bswap rax
{$ELSE}
{$Message Fatal 'ByteSwap64 has not been implemented for this architecture.'}
{$ENDIF}
end;
我不能说此函数是否会带来任何明显的性能好处。在优化代码之前,您应该通过分析和计时代码来识别瓶颈。