delphi - Delphi中的快速Swap64函数

标签 delphi assembly swap

我使用以下函数来交换(无)符号 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;

我不能说这个功能是否会带来任何明显的性能优势。在优化代码之前,您应该通过对代码进行分析和计时来识别瓶颈。

关于delphi - Delphi中的快速Swap64函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586049/

相关文章:

sql - 如何用一条sql删除主明细记录?

c++ - unique_ptr 交换不起作用

delphi - 我可以使用 Delphi XE2 Subversion 与 Subversion 1.7 的集成吗

delphi - TStringList 总是进行换行

c - 如何在内联汇编中声明字符缓冲区?

linux - 为什么我的寄存器常量比较在 NASM Assembly 中不起作用?

汇编语言 st 和 ld

java - 交换数组列表的内容

c++ - std::swap 是否保证通过 ADL 找到非成员交换?

delphi - 在 TDictionary 中使用 "class of"?