【一天一点.NET小知识】运用向量Vector<T>加速求和计算

随着 .NET 版本的演进,从 .NET Standard 2.0 版本开始,支持 Vector<T> 类型。

.NET 8.0 版本开始,大量在 Runtime 提供的各个组件中运用向量计算,​特别是 Linq。
Vector
类型
:表示指定数值类型(适用于并行算法的低级别优化)的单个向量。

假如我们有一个求和函数接受一个int数组入参,当它的长度大于等于8及其倍数以上时,那么我们就可以考虑使用向量Vector<T>加速求和计算。

以下是使用了向量的求和函数代码:

csharp 复制代码
internal class Program
{
    static void Main(string[] args)
    {
        int[] array = Enumerable.Range(1, 32).ToArray();
        int result = Sum(array);
        Console.WriteLine(result);
        Console.ReadKey();
    }

    public static int Sum(int[] numbers)
    {
        ReadOnlySpan<int> span = new ReadOnlySpan<int>(numbers);
        ref int ptr = ref MemoryMarshal.GetReference(span);
        int result = 0;
        int vectorSize = Vector<int>.Count;
        int index;
        int remainder = span.Length % vectorSize;
        int vectorLength = span.Length - remainder;
        Vector<int> vector = Vector<int>.Zero;
        for (index = 0; index < vectorLength; index += vectorSize)
        {
            //Vector<int> vector2 = new Vector<int>(span.Slice(index, vectorSize));
            ref byte address = ref Unsafe.As<int, byte>(ref Unsafe.Add(ref Unsafe.AsRef(in ptr), index));
            Vector<int> vector2 = Unsafe.ReadUnaligned<Vector<int>>(ref address);
            vector += vector2;
        }

        result += Vector.Dot<int>(vector, Vector<int>.One);
        for (; index < span.Length; index++)
        {
            result += Unsafe.Add(ref ptr, index);
        }

        return result;
    }
}

以下是相减函数代码:

csharp 复制代码
static int Sub(int[] numbers)
{
	ReadOnlySpan<int> span = new ReadOnlySpan<int>(numbers);
	ref int ptr = ref MemoryMarshal.GetReference(span);
	int result = 0;
	int vectorSize = Vector<int>.Count;
	int index;
	int remainder = span.Length % vectorSize;
	int vectorLength = span.Length - remainder;
	for (index = 0; index < vectorLength; index += vectorSize)
	{
		ref byte address = ref Unsafe.As<int, byte>(ref Unsafe.Add(ref Unsafe.AsRef(in ptr), index));
		Vector<int> vector = Unsafe.ReadUnaligned<Vector<int>>(ref address);
		result -= Vector.Dot<int>(vector, Vector<int>.One);
	}

	for (; index < span.Length; index++)
	{
		result -= Unsafe.Add(ref ptr, index);
	}

	return result + 2;
}

其它运算,例如相减,也是同理。

以上代码,均可以在 .NET Standard 2.0 及以上版本运行。

当我们向量 Vector<T> 之后,特别是在一些频繁调用计算的场景,将获得指数量级的性能提升。
需要注意的是,向量 Vector<T> 依赖 CPU 硬件的 SIMD 指令集支持,在一些相对较旧的 古董CPU,可能不支持。

PS:

相关推荐
Tummer83632 小时前
C#+WPF+prism+materialdesign创建工具主界面框架
开发语言·c#·wpf
ghost1432 小时前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
yngsqq3 小时前
(for 循环) VS (LINQ) 性能比拼 ——c#
c#·solr·linq
想做后端的小C4 小时前
C# 面向对象 构造函数带参无参细节解析
开发语言·c#·面向对象
炯哈哈4 小时前
【上位机——WPF】App.xml和Application类简介
xml·开发语言·c#·wpf·上位机
bestcxx4 小时前
c# UTC 时间赋值注意事项
c#·utc
酷炫码神4 小时前
C#运算符
开发语言·c#
zybsjn5 小时前
后端系统做国际化改造,生成多语言包
java·python·c#
敲代码的 蜡笔小新6 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
yc_12247 小时前
SqlHelper 实现类,支持多数据库,提供异步操作、自动重试、事务、存储过程、分页、缓存等功能。
数据库·c#