Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 x86 匯編為 C# 打造高速記憶體拷貝:SSE 對齊的極速版本

介紹

大家好,我是 Oleksandr Karpov,這是我第一次發表文章,希望大家喜歡。

本文要展示的是:如何在 C# 與 .NET 環境下用匯編高速拷貝資料。在我的實例裡,程式需要處理一段包含圖片、影片與聲音的視頻資料,記憶體拷貝的吞吐量直接決定效能。

如果你也遇到必須在 C# 裡動用匯編的場景,這提供了一條快速而直接的解法。

背景

理解本文內容,最好具備以下知識:匯編語言、記憶體對齊、C#,以及 Windows 與 .NET 的高階技巧。

要提升資料拷貝速度,關鍵是把記憶體位址按 16 個位元組對齊;否則速度幾乎不會有明顯變化。SSE 指令集中的 movaps、movntps 這類指令,只在 16 位元組對齊時才發揮作用。

Pentium III 以上(KNI/MMX2)與 AMD Athlon(AMD EMMX)這兩種處理器都支援本文用到的 SSE 指令集。

測試環境為 Pentium Dual-Core E5800 3.2GHz、4GB 雙通道記憶體。結果是:16 位元組對齊時比標準方式快約 1.5 倍;未對齊時幾乎沒有改善(約 1.02 倍)。

使用方式

先建立一個預設的 Windows Forms 專案,在窗體上放兩個按鈕和一個 PictureBox(用圖片來測試)。宣告幾個欄位:

string bitmapPath;
Bitmap bmp, bmp2;
BitmapData bmpd, bmpd2;
byte[] buffer = null;

標準方法的按鈕事件:

private void btnStandard_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            return;

        bitmapPath = ofd.FileName;
    }

    // 開啟選取的圖片,並建立一張同尺寸的空白圖片
    OpenImage();

    // 解除鎖定以便讀寫
    UnlockBitmap();

    // 用標準方法把資料從一張圖拷貝到另一張
    CopyImage();

    // 重新鎖定以便顯示
    LockBitmap();

    pictureBox1.Image = bmp2;
}

快速方法只有一行不同——把 CopyImage() 換成 FastCopyImage():

private void btnFast_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            return;

        bitmapPath = ofd.FileName;
    }

    OpenImage();
    UnlockBitmap();

    // 用我們的快速方法拷貝
    FastCopyImage();

    LockBitmap();

    pictureBox1.Image = bmp2;
}

接著實作開啟圖片、鎖定/解鎖,以及標準拷貝:

void OpenImage()
{
  pictureBox1.Image = null;
  buffer = null;
  if (bmp != null)
  {
    bmp.Dispose();
    bmp = null;
  }
  if (bmp2 != null)
  {
    bmp2.Dispose();
    bmp2 = null;
  }
  GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);

  bmp = (Bitmap)Bitmap.FromFile(bitmapPath);

  buffer = new byte[bmp.Width * 4 * bmp.Height];
  bmp2 = new Bitmap(bmp.Width, bmp.Height, bmp.Width * 4, PixelFormat.Format32bppArgb,
    Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0));
}

void UnlockBitmap()
{
  bmpd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite,
    PixelFormat.Format32bppArgb);
  bmpd2 = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadWrite,
    PixelFormat.Format32bppArgb);
}

void LockBitmap()
{
  bmp.UnlockBits(bmpd);
  bmp2.UnlockBits(bmpd2);
}

void CopyImage()
{
  // 啟動碼錶
  Stopwatch sw = new Stopwatch();
  sw.Start();

  // 重複拷貝 10 次
  for (int i = 0; i < 10; i++)
  {
    System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, buffer, 0, buffer.Length);
  }

  sw.Stop();

  MessageBox.Show(sw.ElapsedTicks.ToString());
}

標準做法其實毫不複雜,靠的就是眾所周知的 Marshal.Copy。而快速版本的中間方法更短:

void FastCopyImage()
{
  FastMemCopy.FastMemoryCopy(bmpd.Scan0, bmpd2.Scan0, buffer.Length);
}

FastMemCopy 類別

類別宣告與會用到的型別:

internal static class FastMemCopy
{
  [Flags]
  private enum AllocationTypes : uint
  {
    Commit = 0x1000,  Reserve = 0x2000,
    Reset = 0x80000,  LargePages = 0x20000000,
    Physical = 0x400000,  TopDown = 0x100000,
    WriteWatch = 0x200000
  }

  [Flags]
  private enum MemoryProtections : uint
  {
    Execute = 0x10,     ExecuteRead = 0x20,
    ExecuteReadWrite = 0x40, ExecuteWriteCopy = 0x80,
    NoAccess = 0x01,     ReadOnly = 0x02,
    ReadWrite = 0x04,     WriteCopy = 0x08,
    GuartModifierflag = 0x100, NoCacheModifierflag = 0x200,
    WriteCombineModifierflag = 0x400
  }

  [Flags]
  private enum FreeTypes : uint
  {
    Decommit = 0x4000, Release = 0x8000
  }

  [UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
  private unsafe delegate void FastMemCopyDelegate();

  private static class NativeMethods
  {
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr VirtualAlloc(
      IntPtr lpAddress,
      UIntPtr dwSize,
      AllocationTypes flAllocationType,
      MemoryProtections flProtect);

    [DllImport("kernel32")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool VirtualFree(
      IntPtr lpAddress,
      uint dwSize,
      FreeTypes flFreeType);
  }

主方法的邏輯是:配置一段可執行的記憶體,把我們的機器碼寫進去,用 GetDelegateForFunctionPointer 取得委派,再把來源位址、目的位址與長度這三個參數寫進機器碼尾端預留的空格,然後呼叫它十次並計時。

public static unsafe void FastMemoryCopy(IntPtr src, IntPtr dst, int nBytes)
{
  if (IntPtr.Size == 4)
  {
    // 我們在 32 位元模式

    // 為 asm 方法配置記憶體
    IntPtr p = NativeMethods.VirtualAlloc(
        IntPtr.Zero,
        new UIntPtr((uint)x86_FastMemCopy_New.Length),
        AllocationTypes.Commit | AllocationTypes.Reserve,
        MemoryProtections.ExecuteReadWrite);

    try
    {
        // 把方法位元組複製到配置的記憶體
        Marshal.Copy(x86_FastMemCopy_New, 0, p, x86_FastMemCopy_New.Length);

        // 為我們的方法建立委派
        FastMemCopyDelegate _fastmemcopy =
        (FastMemCopyDelegate)Marshal.GetDelegateForFunctionPointer(p,
        typeof(FastMemCopyDelegate));

        // 移到方法區塊的尾端
        p += x86_FastMemCopy_New.Length;

        // 寫入長度參數
        p -= 8;
        Marshal.Copy(BitConverter.GetBytes((long)nBytes), 0, p, 4);

        // 寫入目的位址參數
        p -= 8;
        Marshal.Copy(BitConverter.GetBytes((long)dst), 0, p, 4);

        // 寫入來源位址參數
        p -= 8;
        Marshal.Copy(BitConverter.GetBytes((long)src), 0, p, 4);

        // 啟動碼錶
        Stopwatch sw = new Stopwatch();
        sw.Start();

        // 重複拷貝 10 次
        for (int i = 0; i < 10; i++)
            _fastmemcopy();

        sw.Stop();

        System.Windows.Forms.MessageBox.Show(sw.ElapsedTicks.ToString());
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        // 釋放配置的記憶體
        NativeMethods.VirtualFree(p, (uint)(x86_FastMemCopy_New.Length),
        FreeTypes.Release);
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
    }
  }
  else if (IntPtr.Size == 8)
  {
    throw new ApplicationException("x64 is not supported yet!");
  }
}

匯編部分做了什麼

匯編碼以帶註註解的位元組陣列形式存在。它的流程可以概括為:

  1. pushad 保存暫存器,透過 ebp 取得方法自身的位址,再從預留位置讀出來源、目的與長度三個參數
  2. 用 and eax, 0x0F 與 and ebx, 0x0F 分別檢查來源與目的是否 16 位元組對齊
  3. 把長度除以 128,以 128 位元組為一輪;每輪用 prefetchnta 預取非暫存資料,再用 8 條 movups(未對齊)或 movaps(已對齊)搬 128 位元組進 xmm0~xmm7
  4. 寫入端依目的對齊與否,選擇 movups 或 movntps(非暫存寫入,繞過快取)
  5. 來源與目的位址各加 128、計數器減一,迴圈直到為 0
  6. 尾端用 and ecx, 0x7F 取得不足 128 的餘數,以 rep movsb 補完
  7. sfence 確保寫入完成,popad 還原暫存器,retn 回到 C#

位元組陣列開頭大致如下(後段是未對齊分支與-aligned 分支的鏡像寫法,以及尾端處理):

private static byte[] x86_FastMemCopy_New = new byte[]
{
  0x90, //nop do nothing
  0x60, //pushad store flag register on stack
  0x95, //xchg ebp, eax eax contains memory address of our method
  0x8B, 0xB5, 0x5A, 0x01, 0x00, 0x00, //mov esi,[ebp][00000015A] get source buffer address
  0x89, 0xF0, //mov eax,esi
  0x83, 0xE0, 0x0F, //and eax,00F will check if it is 16 byte aligned
  0x8B, 0xBD, 0x62, 0x01, 0x00, 0x00, //mov edi,[ebp][000000162] get destination address
  0x89, 0xFB, //mov ebx,edi
  0x83, 0xE3, 0x0F, //and ebx,00F will check if it is 16 byte aligned
  0x8B, 0x8D, 0x6A, 0x01, 0x00, 0x00, //mov ecx,[ebp][00000016A] get number of bytes to copy
  0xC1, 0xE9, 0x07, //shr ecx,7 divide length by 128
  0x85, 0xC9, //test ecx,ecx check if zero
  0x0F, 0x84, 0x1C, 0x01, 0x00, 0x00, //jz 000000146 -&darr; copy the rest
  0x0F, 0x18, 0x06, //prefetchnta [esi] pre-fetch non-temporal source data for reading
  /* ... 其後為 movups / movaps 搬運、movups / movntps 寫入、
     位址遞增與迴圈,以及尾端 rep movsb 與 sfence ... */

  0x00, 0x00, 0x00, 0x00, //source buffer address
  0x00, 0x00, 0x00, 0x00,

  0x00, 0x00, 0x00, 0x00, //destination buffer address
  0x00, 0x00, 0x00, 0x00,

  0x00, 0x00, 0x00, 0x00, //number of bytes to copy-past
  0x00, 0x00, 0x00, 0x00
};

最後那三組 8 個 0,就是前面 C# 程式碼回頭填寫參數的位置——這也是為什麼寫入時要從尾端往前每次退 8 個位元組。

我們透過前面建立的託管委派來呼叫這段匯編。目前只在 32 位元模式下工作,64 位元版本待日後補上,有興趣的人歡迎自行擴充。

興趣點

在實作與測試期間,我發現 prefetchnta 的說明始終不太清楚,連 Intel 的手冊也一樣,只能靠自己摸索與搜尋。另外要特別注意 movntps 與 movaps 的說明:它們只在 16 位元組記憶體對齊時才有效。

C#多線程編程實例 線程與窗體交互【附源碼】 https://www.linuxidc.com/Linux/2014-07/104294.htm

C#數學運算表達式解釋器 https://www.linuxidc.com/Linux/2014-07/104289.htm

在C語言中解析JSON配置文件 https://www.linuxidc.com/Linux/2014-05/101822.htm

C++ Primer Plus 第6版 中文版 清晰有書籤PDF+源代碼 https://www.linuxidc.com/Linux/2014-05/101227.htm

Copyright © Linux教程網 All Rights Reserved