Press "Enter" to skip to content

C# 使用SIMD向量类型加速浮点数组求和运算(2):C#通过Intrinsic直接使用AVX指令集操作 Vector25…

本站内容均来自兴趣收集,如不慎侵害的您的相关权益,请留言告知,我们将尽快删除.谢谢.

作者:

 

目录

 

目录

 

一、缘由

 

在上一篇文章,介绍了.NET的2种向量类型(Vector4、Vector<T>
)。本文来介绍第3种。

 

.NET Core 3.0 增加了对内在函数(Intrinsics Functions)的支持,并增加了第3种向量类型——

 

3. 总位宽固定的向量(Vector of fixed total bit width)。例如 只读结构体Vector64<T>
Vector128<T>
Vector256<T>
,及辅助的静态类 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<byte>.Count
的值为32,换算后是256位,表示它使用了AVX2指令集。可见现在绝大多数PC机的CPU,已支持了AVX2指令集。

 

由于本文是测试浮点求和,用AVX指令集就够了,于是便演示了C#下如何使用AVX指令集来操作Vector256<T>
。且还编写了C++程序,来做对比。

 

二、在C#中使用

 

2.1 文档查看心得

 

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

System.Runtime.Intrinsics:用于提供各种位宽的向量类型,如 只读结构体Vector64<T>
Vector128<T>
Vector256<T>
,及辅助的静态类 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<Double>, Vector256<Double>)
Add(Vector256<Single>, Vector256<Single>)

 

本文只需要处理单精度浮点数,于是只需使用后者。点击它的链接,查看该方法的详细文档。内容如下。

 

__m256 _mm256_add_ps (__m256 a, __m256 b)
VADDPS ymm, ymm, ymm/m256
C#
public static System.Runtime.Intrinsics.Vector256<float> Add (System.Runtime.Intrinsics.Vector256<float> left, System.Runtime.Intrinsics.Vector256<float> right);
参数
leftVector256<Single>
rightVector256<Single>
返回Vector256<Single>

 

此时发现内在函数的文档说明,不如平常的.NET方法的文档详细,例如 参数、返回值 没有说明,且方法简介里是 2行奇怪的文字。

 

其实不用怕,内在函数的文档说明虽然简单,但其实关键内容已经说了,就是方法简介里的“2行奇怪的文字”——

第1行是 对应C语言版的内在函数的申明。如__m256 _mm256_add_ps (__m256 a, __m256 b)
,“_mm256_add_ps”是函数名. __m256是256位的向量类型,对应C#的Vector256<T>
.
第2行是 对应CPU指令的申明。如VADDPS ymm, ymm, ymm/m256
,“VADDPS”是指令名. ymm是256位寄存器,m256是“256位数据的内存地址”,对应C#的Vector256<T>
.

由于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”的说明——

 

Synopsis
__m256 _mm256_add_ps (__m256 a, __m256 b)
#include <immintrin.h>
Instruction: vaddps ymm, ymm, ymm
CPUID Flags: AVX
Description
Add packed single-precision (32-bit) floating-point elements in a and b, and store the results in dst.
Operation
FOR j := 0 to 7
i := j*32
dst[i+31:i] := a[i+31:i] + b[i+31:i]
ENDFOR
dst[MAX:256] := 0
Latency and Throughput
ArchitectureLatencyThroughput (CPI)
Alderlake20.5
Icelake Intel Core40.5
Icelake Xeon40.5
Skylake40.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”的顶部内容,摘录如下。

 

#if NETCOREAPP3_0_OR_GREATER
#define Allow_Intrinsics
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Text;
using System.Runtime.InteropServices;
#if Allow_Intrinsics
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
using System.Runtime.CompilerServices;
namespace BenchmarkVector {
    /// <summary>
    /// Benchmark Vector Demo
    /// </summary>
    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<T>
很像Vector<T>
,也提供了Count属性,能获得元素个数。故可按Count分组分别进行求和(即Map阶段),最后再将这些组的结果加起来(即Reduce阶段)。

 

参考SumVectorT的经验,我们可以写出SumVectorAvx。代码如下。

 

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<float>.Count; // Block width.
    int nBlockWidth = VectorWidth; // Block width.
    int cntBlock = count / nBlockWidth; // Block count.
    int cntRem = count % nBlockWidth; // Remainder count.
    Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
    int p; // Index for src data.
    int i;
    // Load.
    Vector256<float>[] vsrc = new Vector256<float>[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
}

 

对比 SumVectorT,除了将Vector<T>
类型换为Vector256<T>
,因.NET Core 3.0的限制,还有这些变化——

Vector256<T>
未提供构造函数,且Vector256.Create
不支持数组参数(.NET 7才支持数组参数、Span参数),故只能使用最笨的逐个元素传递的办法。
Vector256<T>
不支持运算符重载(.NET 7才支持),需改为使用“Avx.Add”。
Vector256<T>
不支持索引器(.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。

 

代码如下。

 

private static float SumVectorAvxSpan(float[] src, int count, int loops) {
#if Allow_Intrinsics
    float rt = 0; // Result.
    int VectorWidth = Vector256<float>.Count; // Block width.
    int nBlockWidth = VectorWidth; // Block width.
    int cntBlock = count / nBlockWidth; // Block count.
    int cntRem = count % nBlockWidth; // Remainder count.
    Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
    int p; // Index for src data.
    ReadOnlySpan<Vector256<float>> vsrc; // Vector src.
    int i;
    // Body.
    for (int j = 0; j < loops; ++j) {
        // Vector processs.
        vsrc = System.Runtime.InteropServices.MemoryMarshal.Cast<float, Vector256<float> >(new Span<float>(src)); // Reinterpret cast. `float*` to `Vector256<float>*`.
        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
}

 

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语句可以得到数组起始数据的指针,并可用指针地址计算,来代替数组索引计算。代码如下。

 

private static float SumVectorAvxPtr(float[] src, int count, int loops) {
#if Allow_Intrinsics && UNSAFE
    unsafe {
        float rt = 0; // Result.
        int VectorWidth = Vector256<float>.Count; // Block width.
        int nBlockWidth = VectorWidth; // Block width.
        int cntBlock = count / nBlockWidth; // Block count.
        int cntRem = count % nBlockWidth; // Remainder count.
        Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
        Vector256<float> 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.6 完整的BenchmarkVector类

 

在测试方法(Benchmark)里,增加这些函数的测试。

 

此时,完整的BenchmarkVector类的代码如下。

 

#if NETCOREAPP3_0_OR_GREATER
#define Allow_Intrinsics
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Text;
using System.Runtime.InteropServices;
#if Allow_Intrinsics
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
using System.Runtime.CompilerServices;
namespace BenchmarkVector {
    /// <summary>
    /// Benchmark Vector Demo
    /// </summary>
    static class BenchmarkVectorDemo {
        /// <summary>
        /// Is release make.
        /// </summary>
        public static readonly bool IsRelease =
#if DEBUG
            false
#else
            true
#endif
        ;
        /// <summary>
        /// Output Environment.
        /// </summary>
        /// <param name="tw">Output <see cref="TextWriter"/>.</param>
        /// <param name="indent">The indent.</param>
        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<byte>.Count:\t{0}\t# {1}bit", Vector<byte>.Count, Vector<byte>.Count * sizeof(byte) * 8));
            tw.WriteLine(indent + string.Format("Vector<float>.Count:\t{0}\t# {1}bit", Vector<float>.Count, Vector<float>.Count*sizeof(float)*8));
            tw.WriteLine(indent + string.Format("Vector<double>.Count:\t{0}\t# {1}bit", Vector<double>.Count, Vector<double>.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<float>).GetTypeInfo().Assembly;
            tw.WriteLine(string.Format("Vector<T>.Assembly.CodeBase:\t{0}", assembly.CodeBase));
        }
        /// <summary>
        /// Do Benchmark.
        /// </summary>
        /// <param name="tw">Output <see cref="TextWriter"/>.</param>
        /// <param name="indent">The indent.</param>
        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
        }
        /// <summary>
        /// Sum - base.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        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;
        }
        /// <summary>
        /// Sum - Vector4.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        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;
        }
        /// <summary>
        /// Sum - Vector<T>.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        private static float SumVectorT(float[] src, int count, int loops) {
            float rt = 0; // Result.
            int VectorWidth = Vector<float>.Count; // Block width.
            int nBlockWidth = VectorWidth; // Block width.
            int cntBlock = count / nBlockWidth; // Block count.
            int cntRem = count % nBlockWidth; // Remainder count.
            Vector<float> vrt = Vector<float>.Zero; // Vector result.
            int p; // Index for src data.
            int i;
            // Load.
            Vector<float>[] vsrc = new Vector<float>[cntBlock]; // Vector src.
            p = 0;
            for (i = 0; i < vsrc.Length; ++i) {
                vsrc[i] = new Vector<float>(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;
        }
        /// <summary>
        /// Sum - Vector AVX.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        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<float>.Count; // Block width.
            int nBlockWidth = VectorWidth; // Block width.
            int cntBlock = count / nBlockWidth; // Block count.
            int cntRem = count % nBlockWidth; // Remainder count.
            Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
            int p; // Index for src data.
            int i;
            // Load.
            Vector256<float>[] vsrc = new Vector256<float>[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
        }
        /// <summary>
        /// Sum - Vector AVX - Span.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        private static float SumVectorAvxSpan(float[] src, int count, int loops) {
#if Allow_Intrinsics
            float rt = 0; // Result.
            int VectorWidth = Vector256<float>.Count; // Block width.
            int nBlockWidth = VectorWidth; // Block width.
            int cntBlock = count / nBlockWidth; // Block count.
            int cntRem = count % nBlockWidth; // Remainder count.
            Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
            int p; // Index for src data.
            ReadOnlySpan<Vector256<float>> vsrc; // Vector src.
            int i;
            // Body.
            for (int j = 0; j < loops; ++j) {
                // Vector processs.
                vsrc = System.Runtime.InteropServices.MemoryMarshal.Cast<float, Vector256<float> >(new Span<float>(src)); // Reinterpret cast. `float*` to `Vector256<float>*`.
                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
        }
        /// <summary>
        /// Sum - Vector AVX - Ptr.
        /// </summary>
        /// <param name="src">Soure array.</param>
        /// <param name="count">Soure array count.</param>
        /// <param name="loops">Benchmark loops.</param>
        /// <returns>Return the sum value.</returns>
        private static float SumVectorAvxPtr(float[] src, int count, int loops) {
#if Allow_Intrinsics && UNSAFE
            unsafe {
                float rt = 0; // Result.
                int VectorWidth = Vector256<float>.Count; // Block width.
                int nBlockWidth = VectorWidth; // Block width.
                int cntBlock = count / nBlockWidth; // Block count.
                int cntRem = count % nBlockWidth; // Remainder count.
                Vector256<float> vrt = Vector256<float>.Zero; // Vector result.
                Vector256<float> 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版程序的输出信息为:

 

BenchmarkVectorCore30
IsRelease:      True
EnvironmentVariable(PROCESSOR_IDENTIFIER):      Intel64 Family 6 Model 142 Stepping 10, GenuineIntel
Environment.ProcessorCount:     8
Environment.Is64BitOperatingSystem:     True
Environment.Is64BitProcess:     True
Environment.OSVersion:  Microsoft Windows NT 6.2.9200.0
Environment.Version:    3.1.26
RuntimeEnvironment.GetRuntimeDirectory: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\3.1.26\
RuntimeInformation.FrameworkDescription:        .NET Core 3.1.26
BitConverter.IsLittleEndian:    True
IntPtr.Size:    8
Vector.IsHardwareAccelerated:   True
Vector<byte>.Count:     32      # 256bit
Vector<float>.Count:    8       # 256bit
Vector<double>.Count:   4       # 256bit
Vector4.Assembly.CodeBase:      file:///C:/Program Files/dotnet/shared/Microsoft.NETCore.App/3.1.26/System.Numerics.Vectors.dll
Vector<T>.Assembly.CodeBase:    file:///C:/Program Files/dotnet/shared/Microsoft.NETCore.App/3.1.26/System.Private.CoreLib.dll
Benchmark:      count=4096, loops=1000000, countMFlops=4096
SumBase:        6.871948E+10    # msUsed=4938, MFLOPS/s=829.485621709194
SumVector4:     2.748779E+11    # msUsed=1218, MFLOPS/s=3362.8899835796387, scale=4.054187192118227
SumVectorT:     5.497558E+11    # msUsed=609, MFLOPS/s=6725.7799671592775, scale=8.108374384236454
SumVectorAvx:   5.497558E+11    # msUsed=609, MFLOPS/s=6725.7799671592775, scale=8.108374384236454
SumVectorAvxSpan:       5.497558E+11    # msUsed=625, MFLOPS/s=6553.6, scale=7.9008
SumVectorAvxPtr:        5.497558E+11    # msUsed=610, MFLOPS/s=6714.754098360656, scale=8.095081967213115

 

从中可以看出,SumVectorAvx这3个函数的性能,与SumVectorT差不多。这是因为SumVectorT在该电脑上是256bit,表示它内部使用AVX指令集来硬件加速运算,故性能与手工开发AVX的函数差不多。故应尽可能的使用Vector<T>
,这样能适应各种硬件,而不是每一种硬件都开发一套。除非是需要使用内在函数时,才使用Vector256<T>
等类型,但它需要针对不同的硬件平台分别去开发。

 

由于预先转换了数据类型,导致 SumVectorAvx与另外2个函数的性能差不多。但在实际使用时,类型转换带来的内存分配等开销很大,应尽量避免。于是当不允许“不安全代码”时,应该用Span来避免类型转换;而在允许“不安全代码”时,可以用指针来编写。

 

Span
Unsafe code

 

三、在C++中使用

 

3.1 搭建测试项目(BenchmarkVectorCpp)

 

Visual Studio支持在同一个解决方案文件(*.sln)里建立不同编程语言的项目。

 

于是用VS2017打开本文的解决方案文件(BenchmarkVector.sln),添加一个C++的“Console App”项目,命名为“BenchmarkVectorCpp”。

 

随后建立一个源码文件“BenchmarkVectorCpp.cpp”。

 

3.2 基本算法(SumBase)

 

基本算法就是直接写个循环,进行数组求和。

 

可参考先前C#的SumBase,来编写它的C++版函数。代码如下。

 

// Sum - base.
float SumBase(const float* src, size_t count, int loops) {
    float rt = 0; // Result.
    size_t i;
    for (int j = 0; j < loops; ++j) {
        for (i = 0; i < count; ++i) {
            rt += src[i];
        }
    }
    return rt;
}

 

3.3 Avx版算法(SumVectorAvx)

 

VC++虽然没有提供SIMD向量类型,但它很早就支持了AVX的内在函数。引用“immintrin.h”,便可使用AVX的内在函数。

 

可参考先前C#的SumVectorAvxPtr,来编写它的C++版函数。代码如下。

 

// Sum - Vector AVX.
float SumVectorAvx(const float* src, size_t count, int loops) {
    float rt = 0; // Result.
    size_t VectorWidth = sizeof(__m256) / sizeof(float); // Block width.
    size_t nBlockWidth = VectorWidth; // Block width.
    size_t cntBlock = count / nBlockWidth; // Block count.
    size_t cntRem = count % nBlockWidth; // Remainder count.
    __m256 vrt = _mm256_setzero_ps(); // Vector result. [AVX] Set zero.
    __m256 vload; // Vector load.
    const float* p; // Pointer for src data.
    size_t i;
    // Body.
    for (int j = 0; j < loops; ++j) {
        p = src;
        // Vector processs.
        for (i = 0; i < cntBlock; ++i) {
            vload = _mm256_load_ps(p);    // Load. vload = *(*__m256)p;
            vrt = _mm256_add_ps(vrt, vload);    // Add. vrt += vload;
            p += nBlockWidth;
        }
        // Remainder processs.
        for (i = 0; i < cntRem; ++i) {
            rt += p[i];
        }
    }
    // Reduce.
    p = (const float*)&vrt;
    for (i = 0; i < VectorWidth; ++i) {
        rt += p[i];
    }
    return rt;
}

 

_mm256_load_ps、_mm256_add_ps等函数名,在C#的内在函数的文档里可以看到,且可在Intel文档里查看详细说明。详见“ 2.1 文档查看心得”。

 

3.4 测试方法(Benchmark)

 

Benchmark是测试方法,代码如下。

 

// Do Benchmark.
void Benchmark() {
    const size_t alignment = 256 / 8; // sizeof(__m256) / sizeof(BYTE);
    // init.
    clock_t 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 = (float*)_aligned_malloc(sizeof(float)*count, alignment); // new float[count];
    if (NULL == src) {
        printf("Memory alloc fail!");
        return;
    }
    for (int i = 0; i < count; ++i) {
        src[i] = (float)i;
    }
    printf("Benchmark: \tcount=%d, loops=%d, countMFlops=%f
", count, loops, countMFlops);
    // SumBase.
    tickBegin = clock();
    rt = SumBase(src, count, loops);
    msUsed = clock() - tickBegin;
    mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
    printf("SumBase:\t%g\t# msUsed=%d, MFLOPS/s=%f
", rt, (int)msUsed, mFlops);
    double mFlopsBase = mFlops;
    // SumVectorAvx.
    __try {
        tickBegin = clock();
        rt = SumVectorAvx(src, count, loops);
        msUsed = clock() - tickBegin;
        mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
        scale = mFlops / mFlopsBase;
        printf("SumVectorAvx:\t%g\t# msUsed=%d, MFLOPS/s=%f, scale=%f
", rt, (int)msUsed, mFlops, scale);
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        printf("Run SumVectorAvx fail!");
    }
    // done.
    _aligned_free(src);
}

 

因为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的完整代码如下。

 

// BenchmarkVectorCpp.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <immintrin.h>
#include <malloc.h>
#include <stdio.h>
#include <time.h>
#ifndef EXCEPTION_EXECUTE_HANDLER 
#define EXCEPTION_EXECUTE_HANDLER (1)
#endif // !EXCEPTION_EXECUTE_HANDLER 
// Sum - base.
float SumBase(const float* src, size_t count, int loops) {
    float rt = 0; // Result.
    size_t i;
    for (int j = 0; j < loops; ++j) {
        for (i = 0; i < count; ++i) {
            rt += src[i];
        }
    }
    return rt;
}
// Sum - Vector AVX.
float SumVectorAvx(const float* src, size_t count, int loops) {
    float rt = 0; // Result.
    size_t VectorWidth = sizeof(__m256) / sizeof(float); // Block width.
    size_t nBlockWidth = VectorWidth; // Block width.
    size_t cntBlock = count / nBlockWidth; // Block count.
    size_t cntRem = count % nBlockWidth; // Remainder count.
    __m256 vrt = _mm256_setzero_ps(); // Vector result. [AVX] Set zero.
    __m256 vload; // Vector load.
    const float* p; // Pointer for src data.
    size_t i;
    // Body.
    for (int j = 0; j < loops; ++j) {
        p = src;
        // Vector processs.
        for (i = 0; i < cntBlock; ++i) {
            vload = _mm256_load_ps(p);    // Load. vload = *(*__m256)p;
            vrt = _mm256_add_ps(vrt, vload);    // Add. vrt += vload;
            p += nBlockWidth;
        }
        // Remainder processs.
        for (i = 0; i < cntRem; ++i) {
            rt += p[i];
        }
    }
    // Reduce.
    p = (const float*)&vrt;
    for (i = 0; i < VectorWidth; ++i) {
        rt += p[i];
    }
    return rt;
}
// Do Benchmark.
void Benchmark() {
    const size_t alignment = 256 / 8; // sizeof(__m256) / sizeof(BYTE);
    // init.
    clock_t 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 = (float*)_aligned_malloc(sizeof(float)*count, alignment); // new float[count];
    if (NULL == src) {
        printf("Memory alloc fail!");
        return;
    }
    for (int i = 0; i < count; ++i) {
        src[i] = (float)i;
    }
    printf("Benchmark: \tcount=%d, loops=%d, countMFlops=%f
", count, loops, countMFlops);
    // SumBase.
    tickBegin = clock();
    rt = SumBase(src, count, loops);
    msUsed = clock() - tickBegin;
    mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
    printf("SumBase:\t%g\t# msUsed=%d, MFLOPS/s=%f
", rt, (int)msUsed, mFlops);
    double mFlopsBase = mFlops;
    // SumVectorAvx.
    __try {
        tickBegin = clock();
        rt = SumVectorAvx(src, count, loops);
        msUsed = clock() - tickBegin;
        mFlops = countMFlops * CLOCKS_PER_SEC / msUsed;
        scale = mFlops / mFlopsBase;
        printf("SumVectorAvx:\t%g\t# msUsed=%d, MFLOPS/s=%f, scale=%f
", rt, (int)msUsed, mFlops, scale);
    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        printf("Run SumVectorAvx fail!");
    }
    // done.
    _aligned_free(src);
}
int main() {
    printf("BenchmarkVectorCpp
");
    printf("
");
    printf("Pointer size:\t%d
", (int)(sizeof(void*)));
#ifdef _DEBUG
    printf("IsRelease:\tFalse
");
#else
    printf("IsRelease:\tTrue
");
#endif // _DEBUG
#ifdef _MSC_VER
    printf("_MSC_VER:\t%d
", _MSC_VER);
#endif // _MSC_VER
#ifdef __AVX__
    printf("__AVX__:\t%d
", __AVX__);
#endif // __AVX__
    printf("
");
    // Benchmark.
    Benchmark();
}

 

3.6 测试结果

 

在我的电脑(lntel(R) Core(TM) i5-8250U CPU @ 1.60GHz
、Windows 10)上运行时,x64、Release版程序的输出信息为:

 

Pointer size:   8
IsRelease:      True
_MSC_VER:       1916
__AVX__:        1
Benchmark:      count=4096, loops=1000000, countMFlops=4096.000000
SumBase:        6.87195e+10     # msUsed=4938, MFLOPS/s=829.485622
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#使用向量类型的最佳实践——

 

Vector<T>
Vector256<T>

 

源码地址——

https://github.com/zyl910/BenchmarkVector/tree/main/BenchmarkVector2

参考文献

MSDN《Vector256<T>
结构》.https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.intrinsics.vector256-1?view=netcore-3.0
MSDN《Vector256 类》.https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.intrinsics.vector256?view=netcore-3.0
MSDN《Avx 类》.https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.intrinsics.x86.avx?view=netcore-3.0
MSDN《MemoryMarshal 类》.https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.interopservices.memorymarshal?view=netcore-3.0
Tanner Gooding《Hardware Intrinsics in .NET Core》.https://devblogs.microsoft.com/dotnet/hardware-intrinsics-in-net-core/
Intel《Intel® Intrinsics Guide》.https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html
zyl910《[C] 跨平台使用Intrinsic函数范例1——使用SSE、AVX指令集 处理 单精度浮点数组求和(支持vc、gcc,兼容Windows、Linux、Mac)》.https://www.cnblogs.com/zyl910/archive/2012/10/22/simdsumfloat.html
zyl910《[x86]SIMD指令集发展历程表(MMX、SSE、AVX等)》.https://www.cnblogs.com/zyl910/archive/2012/02/26/x86_simd_table.html
zyl910《C# 使用SIMD向量类型加速浮点数组求和运算(1):使用Vector4、Vector<T>
》.https://www.cnblogs.com/zyl910/p/dotnet_simd_BenchmarkVector1.html
wikipedia《Advanced Vector Extensions 2 (AVX2)》.https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#Advanced_Vector_Extensions_2
wikipedia《SSE2 (Streaming SIMD Extensions 2)》.https://en.wikipedia.org/wiki/SSE2

Be First to Comment

发表回复

您的电子邮箱地址不会被公开。