.NET中是否有现成API可将IEnumerable<T>拆分为多个Vector<T>?
.NET中拆分集合为Vector序列的实现方案
.NET没有直接提供一键将大型Array、List或IEnumerable拆分为Vector64/128/512序列的内置API,但可以基于System.Numerics命名空间的类型结合Span/LINQ封装扩展方法,避免手动编写底层循环逻辑。
针对连续内存集合(Array/List)
Array和List的内存是连续的,结合Span<T>可以高效批量创建Vector实例,以下是封装好的扩展方法:
自动适配CPU向量大小的Vector版本
using System.Numerics; public static class VectorCollectionExtensions { public static IEnumerable<Vector<T>> ToVectors<T>(this T[] array) where T : struct { int vectorElementCount = Vector<T>.Count; for (int i = 0; i <= array.Length - vectorElementCount; i += vectorElementCount) { yield return new Vector<T>(array.AsSpan(i, vectorElementCount)); } } public static IEnumerable<Vector<T>> ToVectors<T>(this List<T> list) where T : struct { return list.ToArray().ToVectors(); } }
固定大小的Vector128/256/512版本
如果需要指定具体的向量大小(比如强制用Vector128),可以用对应的类型和Load方法:
using System.Numerics; public static class FixedSizeVectorExtensions { public static IEnumerable<Vector128<T>> ToVector128s<T>(this T[] array) where T : unmanaged { int elementCount = Vector128<T>.Count; for (int i = 0; i <= array.Length - elementCount; i += elementCount) { yield return Vector128.Load(array.AsSpan(i)); } } // Vector256和Vector512的实现逻辑完全一致,替换类型即可 public static IEnumerable<Vector256<T>> ToVector256s<T>(this T[] array) where T : unmanaged { int elementCount = Vector256<T>.Count; for (int i = 0; i <= array.Length - elementCount; i += elementCount) { yield return Vector256.Load(array.AsSpan(i)); } } }
针对IEnumerable
IEnumerable
public static IEnumerable<Vector<T>> ToVectors<T>(this IEnumerable<T> enumerable) where T : struct { return enumerable.ToArray().ToVectors(); }
说明
- 上述方法底层仍有循环,但已封装为可复用的扩展方法,调用时只需
array.ToVectors()或enumerable.ToVectors(),无需手动编写循环逻辑。 Vector<T>.Count会自动适配当前CPU支持的最大向量宽度(比如支持AVX2的CPU会返回8个float元素,对应256位向量)。- Vector128/256/512要求元素类型为
unmanaged(非托管类型),而Vector<T>仅要求struct约束。
内容的提问来源于stack exchange,提问作者forestbat
相关产品推荐
相关产品推荐

