C# 使用SIMD向量类型加速浮点数组求和运算(2):C#通过Intrinsic直接使用A ...

打印 上一主题 下一主题

主题 836|帖子 836|积分 2508

作者:
目录

目录
一、缘由

上一篇文章,介绍了.NET的2种向量类型(Vector4、Vector)。本文来介绍第3种。
.NET Core 3.0 增加了对内在函数(Intrinsics Functions)的支持,并增加了第3种向量类型——
3. 总位宽固定的向量(Vector of fixed total bit width)。例如 只读结构体 Vector64、Vector128、Vector256,及辅助的静态类 Vector64、Vector128、Vector256。这些向量类型没有Nuget包,只能在 .NET Core 3.0或更高版本的.NET环境中运行。
这些向量类型比较特殊,没有直接提供数学运算的函数(到了.NET7,才增加了少量数学函数),而是需要通过内在函数来进行数学运算。
内在函数就是CPU的特殊指令集,其中有向量运算相关的。例如x86体系的向量指令集,有 SSE(Streaming SIMD Extensions,流式SIMD扩展)、AVX(Advanced Vector Extensions,高级矢量扩展)等;且 Arm体系的向量指令集,有 NEON(学名为“Advanced single instruction multiple data”,缩写为“AdvSIMD”)等。
上一篇文章中,发现有硬件加速时,Vector.Count的值为32,换算后是256位,表示它使用了AVX2指令集。可见现在绝大多数PC机的CPU,已支持了AVX2指令集。
由于本文是测试浮点求和,用AVX指令集就够了,于是便演示了C#下如何使用AVX指令集来操作Vector256。且还编写了C++程序,来做对比。
二、在C#中使用

2.1 文档查看心得

与这种向量类型相关的,主要是这3个名称空间——

  • System.Runtime.Intrinsics:用于提供各种位宽的向量类型,如 只读结构体 Vector64、Vector128、Vector256,及辅助的静态类 Vector64、Vector128、Vector256。官方文档说明:包含用于创建和传递各种大小和格式的寄存器状态的类型,用于指令集扩展。有关操作这些寄存器的说明,请参阅 System.Runtime.Intrinsics.X86 和 System.Runtime.Intrinsics.Arm。
  • System.Runtime.Intrinsics.X86:用于提供x86体系的内在函数类,如Avx等。官方文档说明:公开 x86 和 x64 系统的 select 指令集扩展。 对于每个扩展,这些指令集表示为单独的类。 可以通过查询相应类型上的 IsSupported 属性来确定是否支持当前环境中的任何扩展。
  • System.Runtime.Intrinsics.Arm:用于提供Arm体系的内在函数类,如AdvSimd等。官方文档说明:公开 ARM 系统的 select 指令集扩展。 对于每个扩展,这些指令集表示为单独的类。 可以通过查询相应类型上的 IsSupported 属性来确定是否支持当前环境中的任何扩展。
简单来说,“System.Runtime.Intrinsics”用于定义通用的向量类型,随后它的各种子命名空间,以CPU体系来命名。子命名空间里,包含各个内在函数类,每个类对应一套指令集。类中的各个静态方法就是内在函数,对应指令集内的各条指令。
对于每一个内在函数类,都提供静态属性 IsSupported,用于检查当前运行环境是否支持该指令集。例如“Avx.IsSupported”,是用于检测是否支持AVX指令集。
观察子命名空间里的内在函数类,发现有些类的后缀是“64”(如Avx.X64,及Arm里的AdvSimd.Arm64),这些是64位模式下特有的指令集,它们的指令一般比较少。平时应尽量使用后缀不是“64”的类,因为这些它们是 32位或64位 环境都能工作的类。
由于本文是测试用AVX指令集做浮点求和,便去官方文档的“Avx类”里找相关的静态方法。会发现官方充分的利用了.NET平台支持方法名重载(overload)的特征,方法名简洁、易懂,不再像C语言版的内在函数那样有很多奇怪缩写规则。
很快就能能找到求和相关的静态方法“Add”,且它利用了重载,有 Single、Double 这2种签名的函数:

  • Add(Vector256, Vector256)
  • Add(Vector256, Vector256)
本文只需要处理单精度浮点数,于是只需使用后者。点击它的链接,查看该方法的详细文档。内容如下。
  1. __m256 _mm256_add_ps (__m256 a, __m256 b)
  2. VADDPS ymm, ymm, ymm/m256
  3. C#
  4. public static System.Runtime.Intrinsics.Vector256<float> Add (System.Runtime.Intrinsics.Vector256<float> left, System.Runtime.Intrinsics.Vector256<float> right);
  5. 参数
  6. left        Vector256<Single>
  7. right        Vector256<Single>
  8. 返回        Vector256<Single>
复制代码
此时发现内在函数的文档说明,不如平常的.NET方法的文档详细,例如 参数、返回值 没有说明,且方法简介里是 2行奇怪的文字。
其实不用怕,内在函数的文档说明虽然简单,但其实关键内容已经说了,就是方法简介里的“2行奇怪的文字”——

  • 第1行是 对应C语言版的内在函数的申明。如 __m256 _mm256_add_ps (__m256 a, __m256 b),“_mm256_add_ps”是函数名. __m256是256位的向量类型,对应C#的 Vector256 .
  • 第2行是 对应CPU指令的申明。如 VADDPS ymm, ymm, ymm/m256,“VADDPS”是指令名. ymm是256位寄存器,m256是“256位数据的内存地址”,对应C#的 Vector256 .
由于SIMD是同时处理多个数据,传统的“参数、返回值”不容易将处理细节说清楚。于是.NET文档里干脆不说,而是提供了内在函数与指令的申明,让使用者去查CPU厂商的文档,因为CPU厂商的文档很详尽。
例如AVX是Intel提出来的指令集,故可去Intel的文档。Intel已提供了便于在线查询的文档《Intel® Intrinsics Guide》, 地址是“https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html”.
在浏览器打开该地址,然后在屏幕中间的查询框里输入“C语言版的内在函数名”,如“_mm256_add_ps”,查询框的下面便会列出查询结果,随后点击想看的函数就行。由于1条指令对应多个内在函数,若选择用指令名来查询的话,会出现大量匹配,难挑选,故一般使用内在函数名来查询。
摘录一下Intel文档对“_mm256_add_ps”的说明——
  1. Synopsis
  2. __m256 _mm256_add_ps (__m256 a, __m256 b)
  3. #include <immintrin.h>
  4. Instruction: vaddps ymm, ymm, ymm
  5. CPUID Flags: AVX
  6. Description
  7. Add packed single-precision (32-bit) floating-point elements in a and b, and store the results in dst.
  8. Operation
  9. FOR j := 0 to 7
  10.         i := j*32
  11.         dst[i+31:i] := a[i+31:i] + b[i+31:i]
  12. ENDFOR
  13. dst[MAX:256] := 0
  14. Latency and Throughput
  15. Architecture        Latency        Throughput (CPI)
  16. Alderlake        2        0.5
  17. Icelake Intel Core        4        0.5
  18. Icelake Xeon        4        0.5
  19. Skylake        4        0.5
复制代码
可见它除了常规的说明信息外,还提供了“Operation”(伪代码)、“Latency and Throughput”(延迟和吞吐量)。其中对我们最有用的是 “Operation”(伪代码),能清晰的了解该内在函数的操作细节。
例如对于“_mm256_add_ps”,就是将256位数据,分为8组 32位浮点数,分别进行加法运算。高于256位的内容会置零,这个是跟AVX-512有关的,本文不用理会它。
2.2 搭建测试项目(BenchmarkVectorCore30)及处理准备工作

首先需等搭建测试项目。由于.NET Core 3.0才支持这种向量类型,于是得使用VS2019来打开解决方案文件(BenchmarkVector.sln)。
然后建立新项目“BenchmarkVectorCore30”,它是 .NET Core 3.0 控制台程序的项目。并让“BenchmarkVectorCore30”引用共享项目“BenchmarkVector”。
新增的测试函数,也准备放在BenchmarkVectorDemo类里。此时需考虑让 BenchmarkVectorDemo类兼容之前的运行环境(.NET Core 2.0、.NET Framework 4.5 等),于是可以利用条件编译来处理。
由于需要在多个地方进行条件编译判断,故专门定义一个“Allow_Intrinsics”(允许内在函数)的条件编译符号比较好。于是修改了“BenchmarkVectorDemo.cs”的顶部内容,摘录如下。
  1. #if NETCOREAPP3_0_OR_GREATER
  2. #define Allow_Intrinsics
  3. #endif
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Numerics;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Runtime.InteropServices;
  11. #if Allow_Intrinsics
  12. using System.Runtime.Intrinsics;
  13. using System.Runtime.Intrinsics.X86;
  14. #endif
  15. using System.Runtime.CompilerServices;
  16. namespace BenchmarkVector {
  17.     /// <summary>
  18.     /// Benchmark Vector Demo
  19.     /// </summary>
  20.     static class BenchmarkVectorDemo {
复制代码
说明——

  • 用“NETCOREAPP3_0_OR_GREATER”进行条件编译检查,检查通过时定义“Allow_Intrinsics”条件编译符号。因为本文测试的是.NET Core 3.0新增功能,于是使用 .NET Core 时代新增的条件编译符号“NETCOREAPP3_0_OR_GREATER”就行了,不用使用“.NET Framework兼容的条件编译写法”(因为 .NET Framework不支持“NETCOREAPP3_0_OR_GREATER”等内置符号,恰好它也不支持内在函数,故不会有“Allow_Intrinsics”符号,正好满足了本文的条件编译需求)。
  • 在支持内在函数(Allow_Intrinsics)时,使用using指令导入“System.Runtime.Intrinsics”、“System.Runtime.Intrinsics.X86”这2个命名空间。
2.3 编写基于AVX的浮点数组求和函数(SumVectorAvx)

Vector256很像Vector,也提供了Count属性,能获得元素个数。故可按Count分组分别进行求和(即Map阶段),最后再将这些组的结果加起来(即Reduce阶段)。
参考SumVectorT的经验,我们可以写出SumVectorAvx。代码如下。
  1. private static float SumVectorAvx(float[] src, int count, int loops) {
  2. #if Allow_Intrinsics
  3.     float rt = 0; // Result.
  4.     //int VectorWidth = 32 / 4; // sizeof(__m256) / sizeof(float);
  5.     int VectorWidth = Vector256<float>.Count; // Block width.
  6.     int nBlockWidth = VectorWidth; // Block width.
  7.     int cntBlock = count / nBlockWidth; // Block count.
  8.     int cntRem = count % nBlockWidth; // Remainder count.
  9.     Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
  10.     int p; // Index for src data.
  11.     int i;
  12.     // Load.
  13.     Vector256<float>[] vsrc = new Vector256<float>[cntBlock]; // Vector src.
  14.     p = 0;
  15.     for (i = 0; i < cntBlock; ++i) {
  16.         vsrc[i] = Vector256.Create(src[p], src[p + 1], src[p + 2], src[p + 3], src[p + 4], src[p + 5], src[p + 6], src[p + 7]); // Load.
  17.         p += VectorWidth;
  18.     }
  19.     // Body.
  20.     for (int j = 0; j < loops; ++j) {
  21.         // Vector processs.
  22.         for (i = 0; i < cntBlock; ++i) {
  23.             vrt = Avx.Add(vrt, vsrc[i]);    // Add. vrt += vsrc[i];
  24.         }
  25.         // Remainder processs.
  26.         p = cntBlock * nBlockWidth;
  27.         for (i = 0; i < cntRem; ++i) {
  28.             rt += src[p + i];
  29.         }
  30.     }
  31.     // Reduce.
  32.     for (i = 0; i < VectorWidth; ++i) {
  33.         rt += vrt.GetElement(i);
  34.     }
  35.     return rt;
  36. #else
  37.     throw new NotSupportedException();
  38. #endif
  39. }
复制代码
对比 SumVectorT,除了将 Vector 类型换为 Vector256,因.NET Core 3.0的限制,还有这些变化——

  • Vector256 未提供构造函数,且 Vector256.Create 不支持数组参数(.NET 7才支持数组参数、Span参数),故只能使用最笨的逐个元素传递的办法。
  • Vector256 不支持运算符重载(.NET 7才支持),需改为使用“Avx.Add”。
  • Vector256 不支持索引器(.NET 7才支持),需改为扩展方法 GetElement 来获取每个元素的值。
2.4 使用Span改进数据加载(SumVectorAvxSpan)

刚才的SumVectorAvx有个缺点,每次需要“将float[]转为Vector256”,不仅多了运算,且加大了了内存分配的开销。得考虑优化,去掉这一步。
在C/C++里,对于值类型的指针,是支持做 reinterpret_cast(重新解释数据类型) 类型转换的,这样就能避免对数据做类型转换的开销。但是在C#里,只能在“非安全代码”里使用指针与reinterpret_cast,但“非安全代码”一般是尽量少用。
.NET Core 2.1 支持 Span(切片),可以用Span来实现 reinterpret_cast,便解决了这一难题。具体办法是使用 “MemoryMarshal.Cast”来做 reinterpret_cast。
代码如下。
  1. private static float SumVectorAvxSpan(float[] src, int count, int loops) {
  2. #if Allow_Intrinsics
  3.     float rt = 0; // Result.
  4.     int VectorWidth = Vector256<float>.Count; // Block width.
  5.     int nBlockWidth = VectorWidth; // Block width.
  6.     int cntBlock = count / nBlockWidth; // Block count.
  7.     int cntRem = count % nBlockWidth; // Remainder count.
  8.     Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
  9.     int p; // Index for src data.
  10.     ReadOnlySpan<Vector256<float>> vsrc; // Vector src.
  11.     int i;
  12.     // Body.
  13.     for (int j = 0; j < loops; ++j) {
  14.         // Vector processs.
  15.         vsrc = System.Runtime.InteropServices.MemoryMarshal.Cast<float, Vector256<float> >(new Span<float>(src)); // Reinterpret cast. `float*` to `Vector256<float>*`.
  16.         for (i = 0; i < cntBlock; ++i) {
  17.             vrt = Avx.Add(vrt, vsrc[i]);    // Add. vrt += vsrc[i];
  18.         }
  19.         // Remainder processs.
  20.         p = cntBlock * nBlockWidth;
  21.         for (i = 0; i < cntRem; ++i) {
  22.             rt += src[p + i];
  23.         }
  24.     }
  25.     // Reduce.
  26.     for (i = 0; i < VectorWidth; ++i) {
  27.         rt += vrt.GetElement(i);
  28.     }
  29.     return rt;
  30. #else
  31.     throw new NotSupportedException();
  32. #endif
  33. }
复制代码
2.5 使用指针改进数据加载(SumVectorAvxPtr)

查看一下Avx类,发现它提供了加载方法:

  • LoadAlignedVector256(Single*):__m256 _mm256_load_ps (float const * mem_addr)。从已对齐的地址加载。
  • LoadVector256(Single*):__m256 _mm256_loadu_ps (float const * mem_addr)。从未对齐的地址加载。由于.NET中应由.NET自动管理内存地址,故一般情况下应使用它,保险一点。
但这些加载方法都是用指针参数的。故我们需要启用“非安全代码”,才能编写使用了指针的函数。修改项目属性,切换到“Build”页面,Configuration 下拉框选择“All Configurations”,然后勾选“Allow unsafe code”(允许非安全代码),保存,这便允许了“非安全代码”。
随后使用fixed语句可以得到数组起始数据的指针,并可用指针地址计算,来代替数组索引计算。代码如下。
  1. private static float SumVectorAvxPtr(float[] src, int count, int loops) {
  2. #if Allow_Intrinsics && UNSAFE
  3.     unsafe {
  4.         float rt = 0; // Result.
  5.         int VectorWidth = Vector256<float>.Count; // Block width.
  6.         int nBlockWidth = VectorWidth; // Block width.
  7.         int cntBlock = count / nBlockWidth; // Block count.
  8.         int cntRem = count % nBlockWidth; // Remainder count.
  9.         Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
  10.         Vector256<float> vload;
  11.         float* p; // Pointer for src data.
  12.         int i;
  13.         // Body.
  14.         fixed(float* p0 = &src[0]) {
  15.             for (int j = 0; j < loops; ++j) {
  16.                 p = p0;
  17.                 // Vector processs.
  18.                 for (i = 0; i < cntBlock; ++i) {
  19.                     vload = Avx.LoadVector256(p);    // Load. vload = *(*__m256)p;
  20.                     vrt = Avx.Add(vrt, vload);    // Add. vrt += vsrc[i];
  21.                     p += nBlockWidth;
  22.                 }
  23.                 // Remainder processs.
  24.                 for (i = 0; i < cntRem; ++i) {
  25.                     rt += p[i];
  26.                 }
  27.             }
  28.         }
  29.         // Reduce.
  30.         for (i = 0; i < VectorWidth; ++i) {
  31.             rt += vrt.GetElement(i);
  32.         }
  33.         return rt;
  34.     }
  35. #else
  36.     throw new NotSupportedException();
  37. #endif
  38. }
复制代码
2.6 完整的BenchmarkVector类

在测试方法(Benchmark)里,增加这些函数的测试。
此时,完整的BenchmarkVector类的代码如下。
  1. #if NETCOREAPP3_0_OR_GREATER
  2. #define Allow_Intrinsics
  3. #endif
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Numerics;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Runtime.InteropServices;
  11. #if Allow_Intrinsics
  12. using System.Runtime.Intrinsics;
  13. using System.Runtime.Intrinsics.X86;
  14. #endif
  15. using System.Runtime.CompilerServices;
  16. namespace BenchmarkVector {
  17.     /// <summary>
  18.     /// Benchmark Vector Demo
  19.     /// </summary>
  20.     static class BenchmarkVectorDemo {        ///         /// Is release make.        ///         public static readonly bool IsRelease =#if DEBUG            false#else            true#endif        ;        ///         /// Output Environment.        ///         /// Output .        /// The indent.        public static void OutputEnvironment(TextWriter tw, string indent) {            if (null == tw) return;            if (null == indent) indent="";            //string indentNext = indent + "\t";            tw.WriteLine(indent + string.Format("IsRelease:\t{0}", IsRelease));            tw.WriteLine(indent + string.Format("EnvironmentVariable(PROCESSOR_IDENTIFIER):\t{0}", Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER")));            tw.WriteLine(indent + string.Format("Environment.ProcessorCount:\t{0}", Environment.ProcessorCount));            tw.WriteLine(indent + string.Format("Environment.Is64BitOperatingSystem:\t{0}", Environment.Is64BitOperatingSystem));            tw.WriteLine(indent + string.Format("Environment.Is64BitProcess:\t{0}", Environment.Is64BitProcess));            tw.WriteLine(indent + string.Format("Environment.OSVersion:\t{0}", Environment.OSVersion));            tw.WriteLine(indent + string.Format("Environment.Version:\t{0}", Environment.Version));            //tw.WriteLine(indent + string.Format("RuntimeEnvironment.GetSystemVersion:\t{0}", System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion())); // Same Environment.Version            tw.WriteLine(indent + string.Format("RuntimeEnvironment.GetRuntimeDirectory:\t{0}", System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory()));#if (NET47 || NET462 || NET461 || NET46 || NET452 || NET451 || NET45 || NET40 || NET35 || NET20) || (NETSTANDARD1_0)#else            tw.WriteLine(indent + string.Format("RuntimeInformation.FrameworkDescription:\t{0}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription));#endif            tw.WriteLine(indent + string.Format("BitConverter.IsLittleEndian:\t{0}", BitConverter.IsLittleEndian));            tw.WriteLine(indent + string.Format("IntPtr.Size:\t{0}", IntPtr.Size));            tw.WriteLine(indent + string.Format("Vector.IsHardwareAccelerated:\t{0}", Vector.IsHardwareAccelerated));            tw.WriteLine(indent + string.Format("Vector.Count:\t{0}\t# {1}bit", Vector.Count, Vector.Count * sizeof(byte) * 8));            tw.WriteLine(indent + string.Format("Vector.Count:\t{0}\t# {1}bit", Vector.Count, Vector.Count*sizeof(float)*8));            tw.WriteLine(indent + string.Format("Vector.Count:\t{0}\t# {1}bit", Vector.Count, Vector.Count * sizeof(double) * 8));            Assembly assembly = typeof(Vector4).GetTypeInfo().Assembly;            //tw.WriteLine(string.Format("Vector4.Assembly:\t{0}", assembly));            tw.WriteLine(string.Format("Vector4.Assembly.CodeBase:\t{0}", assembly.CodeBase));            assembly = typeof(Vector).GetTypeInfo().Assembly;            tw.WriteLine(string.Format("Vector.Assembly.CodeBase:\t{0}", assembly.CodeBase));        }        ///         /// Do Benchmark.        ///         /// Output .        /// The indent.        public static void Benchmark(TextWriter tw, string indent) {            if (null == tw) return;            if (null == indent) indent = "";            //string indentNext = indent + "\t";            // init.            int tickBegin, msUsed;            double mFlops; // MFLOPS/s .            double scale;            float rt;            const int count = 1024*4;            const int loops = 1000 * 1000;            //const int loops = 1;            const double countMFlops = count * (double)loops / (1000.0 * 1000);            float[] src = new float[count];            for(int i=0; i< count; ++i) {                src[i] = i;            }            tw.WriteLine(indent + string.Format("Benchmark: \tcount={0}, loops={1}, countMFlops={2}", count, loops, countMFlops));            // SumBase.            tickBegin = Environment.TickCount;            rt = SumBase(src, count, loops);            msUsed = Environment.TickCount - tickBegin;            mFlops = countMFlops * 1000 / msUsed;            tw.WriteLine(indent + string.Format("SumBase:\t{0}\t# msUsed={1}, MFLOPS/s={2}", rt, msUsed, mFlops));            double mFlopsBase = mFlops;            // SumVector4.            tickBegin = Environment.TickCount;            rt = SumVector4(src, count, loops);            msUsed = Environment.TickCount - tickBegin;            mFlops = countMFlops * 1000 / msUsed;            scale = mFlops / mFlopsBase;            tw.WriteLine(indent + string.Format("SumVector4:\t{0}\t# msUsed={1}, MFLOPS/s={2}, scale={3}", rt, msUsed, mFlops, scale));            // SumVectorT.            tickBegin = Environment.TickCount;            rt = SumVectorT(src, count, loops);            msUsed = Environment.TickCount - tickBegin;            mFlops = countMFlops * 1000 / msUsed;            scale = mFlops / mFlopsBase;            tw.WriteLine(indent + string.Format("SumVectorT:\t{0}\t# msUsed={1}, MFLOPS/s={2}, scale={3}", rt, msUsed, mFlops, scale));            // SumVectorAvx.#if Allow_Intrinsics            if (Avx.IsSupported) {                try {                    tickBegin = Environment.TickCount;                    rt = SumVectorAvx(src, count, loops);                    msUsed = Environment.TickCount - tickBegin;                    mFlops = countMFlops * 1000 / msUsed;                    scale = mFlops / mFlopsBase;                    tw.WriteLine(indent + string.Format("SumVectorAvx:\t{0}\t# msUsed={1}, MFLOPS/s={2}, scale={3}", rt, msUsed, mFlops, scale));                    // SumVectorAvxSpan.                    tickBegin = Environment.TickCount;                    rt = SumVectorAvxSpan(src, count, loops);                    msUsed = Environment.TickCount - tickBegin;                    mFlops = countMFlops * 1000 / msUsed;                    scale = mFlops / mFlopsBase;                    tw.WriteLine(indent + string.Format("SumVectorAvxSpan:\t{0}\t# msUsed={1}, MFLOPS/s={2}, scale={3}", rt, msUsed, mFlops, scale));                    // SumVectorAvxPtr.                    tickBegin = Environment.TickCount;                    rt = SumVectorAvxPtr(src, count, loops);                    msUsed = Environment.TickCount - tickBegin;                    mFlops = countMFlops * 1000 / msUsed;                    scale = mFlops / mFlopsBase;                    tw.WriteLine(indent + string.Format("SumVectorAvxPtr:\t{0}\t# msUsed={1}, MFLOPS/s={2}, scale={3}", rt, msUsed, mFlops, scale));                } catch (Exception ex) {                    tw.WriteLine("Run SumVectorAvx fail!");                    tw.WriteLine(ex);                }            }#endif        }        ///         /// Sum - base.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumBase(float[] src, int count, int loops) {            float rt = 0; // Result.            for (int j=0; j< loops; ++j) {                for(int i=0; i< count; ++i) {                    rt += src[i];                }            }            return rt;        }        ///         /// Sum - Vector4.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumVector4(float[] src, int count, int loops) {            float rt = 0; // Result.            const int VectorWidth = 4;            int nBlockWidth = VectorWidth; // Block width.            int cntBlock = count / nBlockWidth; // Block count.            int cntRem = count % nBlockWidth; // Remainder count.            Vector4 vrt = Vector4.Zero; // Vector result.            int p; // Index for src data.            int i;            // Load.            Vector4[] vsrc = new Vector4[cntBlock]; // Vector src.            p = 0;            for (i = 0; i < vsrc.Length; ++i) {                vsrc[i] = new Vector4(src[p], src[p + 1], src[p + 2], src[p + 3]);                p += VectorWidth;            }            // Body.            for (int j = 0; j < loops; ++j) {                // Vector processs.                for (i = 0; i < cntBlock; ++i) {                    // Equivalent to scalar model: rt += src[i];                    vrt += vsrc[i]; // Add.                }                // Remainder processs.                p = cntBlock * nBlockWidth;                for (i = 0; i < cntRem; ++i) {                    rt += src[p + i];                }            }            // Reduce.            rt += vrt.X + vrt.Y + vrt.Z + vrt.W;            return rt;        }        ///         /// Sum - Vector.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumVectorT(float[] src, int count, int loops) {            float rt = 0; // Result.            int VectorWidth = Vector.Count; // Block width.            int nBlockWidth = VectorWidth; // Block width.            int cntBlock = count / nBlockWidth; // Block count.            int cntRem = count % nBlockWidth; // Remainder count.            Vector vrt = Vector.Zero; // Vector result.            int p; // Index for src data.            int i;            // Load.            Vector[] vsrc = new Vector[cntBlock]; // Vector src.            p = 0;            for (i = 0; i < vsrc.Length; ++i) {                vsrc[i] = new Vector(src, p);                p += VectorWidth;            }            // Body.            for (int j = 0; j < loops; ++j) {                // Vector processs.                for (i = 0; i < cntBlock; ++i) {                    vrt += vsrc[i]; // Add.                }                // Remainder processs.                p = cntBlock * nBlockWidth;                for (i = 0; i < cntRem; ++i) {                    rt += src[p + i];                }            }            // Reduce.            for (i = 0; i < VectorWidth; ++i) {                rt += vrt[i];            }            return rt;        }        ///         /// Sum - Vector AVX.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumVectorAvx(float[] src, int count, int loops) {#if Allow_Intrinsics            float rt = 0; // Result.            //int VectorWidth = 32 / 4; // sizeof(__m256) / sizeof(float);            int VectorWidth = Vector256.Count; // Block width.            int nBlockWidth = VectorWidth; // Block width.            int cntBlock = count / nBlockWidth; // Block count.            int cntRem = count % nBlockWidth; // Remainder count.            Vector256 vrt = Vector256.Zero; // Vector result.            int p; // Index for src data.            int i;            // Load.            Vector256[] vsrc = new Vector256[cntBlock]; // Vector src.            p = 0;            for (i = 0; i < cntBlock; ++i) {                vsrc[i] = Vector256.Create(src[p], src[p + 1], src[p + 2], src[p + 3], src[p + 4], src[p + 5], src[p + 6], src[p + 7]); // Load.                p += VectorWidth;            }            // Body.            for (int j = 0; j < loops; ++j) {                // Vector processs.                for (i = 0; i < cntBlock; ++i) {                    vrt = Avx.Add(vrt, vsrc[i]);    // Add. vrt += vsrc[i];                }                // Remainder processs.                p = cntBlock * nBlockWidth;                for (i = 0; i < cntRem; ++i) {                    rt += src[p + i];                }            }            // Reduce.            for (i = 0; i < VectorWidth; ++i) {                rt += vrt.GetElement(i);            }            return rt;#else            throw new NotSupportedException();#endif        }        ///         /// Sum - Vector AVX - Span.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumVectorAvxSpan(float[] src, int count, int loops) {#if Allow_Intrinsics            float rt = 0; // Result.            int VectorWidth = Vector256.Count; // Block width.            int nBlockWidth = VectorWidth; // Block width.            int cntBlock = count / nBlockWidth; // Block count.            int cntRem = count % nBlockWidth; // Remainder count.            Vector256 vrt = Vector256.Zero; // Vector result.            int p; // Index for src data.            ReadOnlySpan vsrc; // Vector src.            int i;            // Body.            for (int j = 0; j < loops; ++j) {                // Vector processs.                vsrc = System.Runtime.InteropServices.MemoryMarshal.Cast(new Span(src)); // Reinterpret cast. `float*` to `Vector256*`.                for (i = 0; i < cntBlock; ++i) {                    vrt = Avx.Add(vrt, vsrc[i]);    // Add. vrt += vsrc[i];                }                // Remainder processs.                p = cntBlock * nBlockWidth;                for (i = 0; i < cntRem; ++i) {                    rt += src[p + i];                }            }            // Reduce.            for (i = 0; i < VectorWidth; ++i) {                rt += vrt.GetElement(i);            }            return rt;#else            throw new NotSupportedException();#endif        }        ///         /// Sum - Vector AVX - Ptr.        ///         /// Soure array.        /// Soure array count.        /// Benchmark loops.        /// Return the sum value.        private static float SumVectorAvxPtr(float[] src, int count, int loops) {#if Allow_Intrinsics && UNSAFE            unsafe {                float rt = 0; // Result.                int VectorWidth = Vector256.Count; // Block width.                int nBlockWidth = VectorWidth; // Block width.                int cntBlock = count / nBlockWidth; // Block count.                int cntRem = count % nBlockWidth; // Remainder count.                Vector256 vrt = Vector256.Zero; // Vector result.                Vector256 vload;                float* p; // Pointer for src data.                int i;                // Body.                fixed(float* p0 = &src[0]) {                    for (int j = 0; j < loops; ++j) {                        p = p0;                        // Vector processs.                        for (i = 0; i < cntBlock; ++i) {                            vload = Avx.LoadVector256(p);    // Load. vload = *(*__m256)p;                            vrt = Avx.Add(vrt, vload);    // Add. vrt += vsrc[i];                            p += nBlockWidth;                        }                        // Remainder processs.                        for (i = 0; i < cntRem; ++i) {                            rt += p[i];                        }                    }                }                // Reduce.                for (i = 0; i < VectorWidth; ++i) {                    rt += vrt.GetElement(i);                }                return rt;            }#else            throw new NotSupportedException();#endif        }    }}
复制代码
2.7 测试结果

在我的电脑(lntel(R) Core(TM) i5-8250U CPU @ 1.60GHz、Windows 10)上运行时,x64、Release版程序的输出信息为:
  1. BenchmarkVectorCore30
  2. IsRelease:      True
  3. EnvironmentVariable(PROCESSOR_IDENTIFIER):      Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
  4. Environment.ProcessorCount:     8
  5. Environment.Is64BitOperatingSystem:     True
  6. Environment.Is64BitProcess:     True
  7. Environment.OSVersion:  Microsoft Windows NT 6.2.9200.0
  8. Environment.Version:    3.1.26
  9. RuntimeEnvironment.GetRuntimeDirectory: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.26\
  10. RuntimeInformation.FrameworkDescription:        .NET Core 3.1.26
  11. BitConverter.IsLittleEndian:    True
  12. IntPtr.Size:    8
  13. Vector.IsHardwareAccelerated:   True
  14. Vector<byte>.Count:     32      # 256bit
  15. Vector<float>.Count:    8       # 256bit
  16. Vector<double>.Count:   4       # 256bit
  17. Vector4.Assembly.CodeBase:      file:///C:/Program Files/dotnet/shared/Microsoft.NETCore.App/3.1.26/System.Numerics.Vectors.dll
  18. Vector<T>.Assembly.CodeBase:    file:///C:/Program Files/dotnet/shared/Microsoft.NETCore.App/3.1.26/System.Private.CoreLib.dll
  19. Benchmark:      count=4096, loops=1000000, countMFlops=4096
  20. SumBase:        6.871948E+10    # msUsed=4938, MFLOPS/s=829.485621709194
  21. SumVector4:     2.748779E+11    # msUsed=1218, MFLOPS/s=3362.8899835796387, scale=4.054187192118227
  22. SumVectorT:     5.497558E+11    # msUsed=609, MFLOPS/s=6725.7799671592775, scale=8.108374384236454
  23. SumVectorAvx:   5.497558E+11    # msUsed=609, MFLOPS/s=6725.7799671592775, scale=8.108374384236454
  24. SumVectorAvxSpan:       5.497558E+11    # msUsed=625, MFLOPS/s=6553.6, scale=7.9008
  25. SumVectorAvxPtr:        5.497558E+11    # msUsed=610, MFLOPS/s=6714.754098360656, scale=8.095081967213115
复制代码
从中可以看出,SumVectorAvx这3个函数的性能,与SumVectorT差不多。这是因为SumVectorT在该电脑上是256bit,表示它内部使用AVX指令集来硬件加速运算,故性能与手工开发AVX的函数差不多。故应尽可能的使用 Vector,这样能适应各种硬件,而不是每一种硬件都开发一套。除非是需要使用内在函数时,才使用 Vector256 等类型,但它需要针对不同的硬件平台分别去开发。
由于预先转换了数据类型,导致 SumVectorAvx与另外2个函数的性能差不多。但在实际使用时,类型转换带来的内存分配等开销很大,应尽量避免。于是当不允许“不安全代码”时,应该用Span来避免类型转换;而在允许“不安全代码”时,可以用指针来编写。

  • Span(切片):优点是无需启用“不安全代码”,能实现reinterpret_cast等操作来避免多余的开销,自带数据越界检查。缺点是部分内在函数不支持Span(内建函数到了.NET7,才全面改善Span的支持),性能比指针稍低(因多了数据越界检查)。
  • Unsafe code(不安全代码):优点是能使用所有内在函数,能充分利用指针的reinterpret_cast等特点来减少多余的开销,便于移植 C/C++ 的SIMD代码,性能比Span高(因没有数据越界检查)。缺点是需要启用“不安全代码”,且程序员疏忽时会遇到 数据越界 等问题。
三、在C++中使用

3.1 搭建测试项目(BenchmarkVectorCpp)

Visual Studio支持在同一个解决方案文件(*.sln)里建立不同编程语言的项目。
于是用VS2017打开本文的解决方案文件(BenchmarkVector.sln),添加一个C++的“Console App”项目,命名为“BenchmarkVectorCpp”。
随后建立一个源码文件“BenchmarkVectorCpp.cpp”。
3.2 基本算法(SumBase)

基本算法就是直接写个循环,进行数组求和。
可参考先前C#的SumBase,来编写它的C++版函数。代码如下。
  1. // Sum - base.
  2. float SumBase(const float* src, size_t count, int loops) {
  3.     float rt = 0; // Result.
  4.     size_t i;
  5.     for (int j = 0; j < loops; ++j) {
  6.         for (i = 0; i < count; ++i) {
  7.             rt += src[i];
  8.         }
  9.     }
  10.     return rt;
  11. }
复制代码
3.3 Avx版算法(SumVectorAvx)

VC++虽然没有提供SIMD向量类型,但它很早就支持了AVX的内在函数。引用“immintrin.h”,便可使用AVX的内在函数。
可参考先前C#的SumVectorAvxPtr,来编写它的C++版函数。代码如下。
  1. // Sum - Vector AVX.
  2. float SumVectorAvx(const float* src, size_t count, int loops) {
  3.     float rt = 0; // Result.
  4.     size_t VectorWidth = sizeof(__m256) / sizeof(float); // Block width.
  5.     size_t nBlockWidth = VectorWidth; // Block width.
  6.     size_t cntBlock = count / nBlockWidth; // Block count.
  7.     size_t cntRem = count % nBlockWidth; // Remainder count.
  8.     __m256 vrt = _mm256_setzero_ps(); // Vector result. [AVX] Set zero.
  9.     __m256 vload; // Vector load.
  10.     const float* p; // Pointer for src data.
  11.     size_t i;
  12.     // Body.
  13.     for (int j = 0; j < loops; ++j) {
  14.         p = src;
  15.         // Vector processs.
  16.         for (i = 0; i < cntBlock; ++i) {
  17.             vload = _mm256_load_ps(p);    // Load. vload = *(*__m256)p;
  18.             vrt = _mm256_add_ps(vrt, vload);    // Add. vrt += vload;
  19.             p += nBlockWidth;
  20.         }
  21.         // Remainder processs.
  22.         for (i = 0; i < cntRem; ++i) {
  23.             rt += p[i];
  24.         }
  25.     }
  26.     // Reduce.
  27.     p = (const float*)&vrt;
  28.     for (i = 0; i < VectorWidth; ++i) {
  29.         rt += p[i];
  30.     }
  31.     return rt;
  32. }
复制代码
_mm256_load_ps、_mm256_add_ps等函数名,在C#的内在函数的文档里可以看到,且可在Intel文档里查看详细说明。详见“ 2.1 文档查看心得”。
3.4 测试方法(Benchmark)

Benchmark是测试方法,代码如下。
  1. // Do Benchmark.
  2. void Benchmark() {
  3.     const size_t alignment = 256 / 8; // sizeof(__m256) / sizeof(BYTE);
  4.     // init.
  5.     clock_t tickBegin, msUsed;
  6.     double mFlops; // MFLOPS/s .
  7.     double scale;
  8.     float rt;
  9.     const int count = 1024 * 4;
  10.     const int loops = 1000 * 1000;
  11.     //const int loops = 1;
  12.     const double countMFlops = count * (double)loops / (1000.0 * 1000);
  13.     float* src = (float*)_aligned_malloc(sizeof(float)*count, alignment); // new float[count];
  14.     if (NULL == src) {
  15.         printf("Memory alloc fail!");
  16.         return;
  17.     }
  18.     for (int i = 0; i < count; ++i) {
  19.         src[i] = (float)i;
  20.     }
  21.     printf("Benchmark: \tcount=%d, loops=%d, countMFlops=%f\n", count, loops, countMFlops);
  22.     // SumBase.
  23.     tickBegin = clock();
  24.     rt = SumBase(src, count, loops);
  25.     msUsed = clock() - tickBegin;
  26.     mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
  27.     printf("SumBase:\t%g\t# msUsed=%d, MFLOPS/s=%f\n", rt, (int)msUsed, mFlops);
  28.     double mFlopsBase = mFlops;
  29.     // SumVectorAvx.
  30.     __try {
  31.         tickBegin = clock();
  32.         rt = SumVectorAvx(src, count, loops);
  33.         msUsed = clock() - tickBegin;
  34.         mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
  35.         scale = mFlops / mFlopsBase;
  36.         printf("SumVectorAvx:\t%g\t# msUsed=%d, MFLOPS/s=%f, scale=%f\n", rt, (int)msUsed, mFlops, scale);
  37.     }
  38.     __except (EXCEPTION_EXECUTE_HANDLER) {
  39.         printf("Run SumVectorAvx fail!");
  40.     }
  41.     // done.
  42.     _aligned_free(src);
  43. }
复制代码
因为AVX对于地址对齐的数据,性能最好。于是使用了 _aligned_malloc 分配内存,用 _aligned_free 释放内存。
C语言标准库里提供了clock函数来计时,CLOCKS_PER_SEC常量是它在每秒的间隔值。于是便能计算出耗时时间。
因C++或VC++官方库里未提供检测AVX指令集的办法,而手工写一个的话,太影响篇幅。于是本文用了一个简单的办法,利用VC++的SEH(Structured Exception Handling,结构化异常处理)来做异常处理,当“__try”块运行时发现不支持AVX指令集时,会进入“__except”块。
3.5 BenchmarkVectorCpp.cpp的完整代码

BenchmarkVectorCpp.cpp的完整代码如下。
  1. // BenchmarkVectorCpp.cpp : This file contains the 'main' function. Program execution begins and ends there.//#include #include #include #include #ifndef EXCEPTION_EXECUTE_HANDLER #define EXCEPTION_EXECUTE_HANDLER (1)#endif // !EXCEPTION_EXECUTE_HANDLER // Sum - base.
  2. float SumBase(const float* src, size_t count, int loops) {
  3.     float rt = 0; // Result.
  4.     size_t i;
  5.     for (int j = 0; j < loops; ++j) {
  6.         for (i = 0; i < count; ++i) {
  7.             rt += src[i];
  8.         }
  9.     }
  10.     return rt;
  11. }// Sum - Vector AVX.
  12. float SumVectorAvx(const float* src, size_t count, int loops) {
  13.     float rt = 0; // Result.
  14.     size_t VectorWidth = sizeof(__m256) / sizeof(float); // Block width.
  15.     size_t nBlockWidth = VectorWidth; // Block width.
  16.     size_t cntBlock = count / nBlockWidth; // Block count.
  17.     size_t cntRem = count % nBlockWidth; // Remainder count.
  18.     __m256 vrt = _mm256_setzero_ps(); // Vector result. [AVX] Set zero.
  19.     __m256 vload; // Vector load.
  20.     const float* p; // Pointer for src data.
  21.     size_t i;
  22.     // Body.
  23.     for (int j = 0; j < loops; ++j) {
  24.         p = src;
  25.         // Vector processs.
  26.         for (i = 0; i < cntBlock; ++i) {
  27.             vload = _mm256_load_ps(p);    // Load. vload = *(*__m256)p;
  28.             vrt = _mm256_add_ps(vrt, vload);    // Add. vrt += vload;
  29.             p += nBlockWidth;
  30.         }
  31.         // Remainder processs.
  32.         for (i = 0; i < cntRem; ++i) {
  33.             rt += p[i];
  34.         }
  35.     }
  36.     // Reduce.
  37.     p = (const float*)&vrt;
  38.     for (i = 0; i < VectorWidth; ++i) {
  39.         rt += p[i];
  40.     }
  41.     return rt;
  42. }// Do Benchmark.
  43. void Benchmark() {
  44.     const size_t alignment = 256 / 8; // sizeof(__m256) / sizeof(BYTE);
  45.     // init.
  46.     clock_t tickBegin, msUsed;
  47.     double mFlops; // MFLOPS/s .
  48.     double scale;
  49.     float rt;
  50.     const int count = 1024 * 4;
  51.     const int loops = 1000 * 1000;
  52.     //const int loops = 1;
  53.     const double countMFlops = count * (double)loops / (1000.0 * 1000);
  54.     float* src = (float*)_aligned_malloc(sizeof(float)*count, alignment); // new float[count];
  55.     if (NULL == src) {
  56.         printf("Memory alloc fail!");
  57.         return;
  58.     }
  59.     for (int i = 0; i < count; ++i) {
  60.         src[i] = (float)i;
  61.     }
  62.     printf("Benchmark: \tcount=%d, loops=%d, countMFlops=%f\n", count, loops, countMFlops);
  63.     // SumBase.
  64.     tickBegin = clock();
  65.     rt = SumBase(src, count, loops);
  66.     msUsed = clock() - tickBegin;
  67.     mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
  68.     printf("SumBase:\t%g\t# msUsed=%d, MFLOPS/s=%f\n", rt, (int)msUsed, mFlops);
  69.     double mFlopsBase = mFlops;
  70.     // SumVectorAvx.
  71.     __try {
  72.         tickBegin = clock();
  73.         rt = SumVectorAvx(src, count, loops);
  74.         msUsed = clock() - tickBegin;
  75.         mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
  76.         scale = mFlops / mFlopsBase;
  77.         printf("SumVectorAvx:\t%g\t# msUsed=%d, MFLOPS/s=%f, scale=%f\n", rt, (int)msUsed, mFlops, scale);
  78.     }
  79.     __except (EXCEPTION_EXECUTE_HANDLER) {
  80.         printf("Run SumVectorAvx fail!");
  81.     }
  82.     // done.
  83.     _aligned_free(src);
  84. }int main() {    printf("BenchmarkVectorCpp\n");    printf("\n");    printf("Pointer size:\t%d\n", (int)(sizeof(void*)));#ifdef _DEBUG    printf("IsRelease:\tFalse\n");#else    printf("IsRelease:\tTrue\n");#endif // _DEBUG#ifdef _MSC_VER    printf("_MSC_VER:\t%d\n", _MSC_VER);#endif // _MSC_VER#ifdef __AVX__    printf("__AVX__:\t%d\n", __AVX__);#endif // __AVX__    printf("\n");    // Benchmark.    Benchmark();}
复制代码
3.6 测试结果

在我的电脑(lntel(R) Core(TM) i5-8250U CPU @ 1.60GHz、Windows 10)上运行时,x64、Release版程序的输出信息为:
  1. Pointer size:   8
  2. IsRelease:      True
  3. _MSC_VER:       1916
  4. __AVX__:        1
  5. Benchmark:      count=4096, loops=1000000, countMFlops=4096.000000
  6. SumBase:        6.87195e+10     # msUsed=4938, MFLOPS/s=829.485622
  7. SumVectorAvx:   5.49756e+11     # msUsed=616, MFLOPS/s=6649.350649, scale=8.016234
复制代码
从中可以看出——

  • SumBase:C++版(MFLOPS/s=829.485622),与C#版(MFLOPS/s=829.485621709194)的性能相同。
  • SumVectorAvx:C++版(MFLOPS/s=6649.350649),与C#版(MFLOPS/s=6714.754098360656)的性能几乎相同。
也就说,对于使用内在函数来做SIMD,C++与C#的性能是相同。故可以根据项目需要,选择最合适的开发语言就行。
四、小结

C#使用向量类型的最佳实践——

  • 若仅需要使用单精度浮点类型(float),且是开发数学上的向量运算相关的功能,可根据业务上对向量运算的要求,使用维度匹配的向量类(例如 2维向量处理时用Vector2、3维向量处理时用Vector3、3维齐次向量处理时用Vector4)。其他情况下,至少应编写一套传统的、不使用向量类型的代码。
  • 若某项计算任务需要进一步做性能优化、且它的工作比较适合SIMD处理时,可以再开发一套基于 Vector 的向量代码。在使用时别忘了检查是否支持硬件加速,若不支持,应退回到使用传统代码。
  • 若发现内在函数能带来很大的提升时,可考虑使用内在函数,开发基于总位宽固定的向量的代码(如 Vector256 )。在使用时别忘了检查当前平台是否支持该内在函数,若不支持,应退回到使用前面的方案(第1~2条)。
源码地址——
https://github.com/zyl910/BenchmarkVector/tree/main/BenchmarkVector2
参考文献

    出处:http://www.cnblogs.com/zyl910/    版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0.
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

魏晓东

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表