Skip to content

Instantly share code, notes, and snippets.

@davidglassborow
Forked from xoofx/BatchSimdDot.cs
Created November 9, 2024 13:55
Show Gist options
  • Select an option

  • Save davidglassborow/f79a7f8e8fe5d156d7546e3d964ff3e8 to your computer and use it in GitHub Desktop.

Select an option

Save davidglassborow/f79a7f8e8fe5d156d7546e3d964ff3e8 to your computer and use it in GitHub Desktop.

Revisions

  1. @xoofx xoofx created this gist Sep 2, 2024.
    43 changes: 43 additions & 0 deletions BatchSimdDot.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // Comment about https://mastodon.social/@[email protected]/113064780292323247
    // https://brandewinder.com/2024/09/01/should-i-use-simd-vectors/
    using System.Numerics;
    using System.Runtime.InteropServices;
    using System.Runtime.Intrinsics;

    public class VectorProcessor
    {
    public static float Take2(float[] left, float[] right)
    {
    var size = left.Length;
    var s1 = new ReadOnlySpan<float>(left);
    var s2 = new ReadOnlySpan<float>(right);
    var total = 0.0f;
    // Use Vector<float>.Count, don't hardcode
    for (int i = 0; i < size / Vector<float>.Count; i++)
    {
    var s = Vector<float>.Count * i;
    var v1 = new Vector<float>(s1.Slice(s, Vector<float>.Count));
    var v2 = new Vector<float>(s2.Slice(s, Vector<float>.Count));
    var diff = v1 - v2;
    total += Vector.Dot(diff, diff);
    }

    return MathF.Sqrt(total);
    }

    public static float TakeFaster(float[] left, float[] right)
    {
    var s1 = MemoryMarshal.Cast<float, Vector<float>>(new ReadOnlySpan<float>(left));
    var s2 = MemoryMarshal.Cast<float, Vector<float>>(new ReadOnlySpan<float>(right));
    var total = 0.0f;
    for (int i = 0; i < s1.Length && i < s2.Length; i++)
    {
    var v1 = s1[i];
    var v2 = s2[i];
    var diff = v1 - v2;
    total += Vector.Dot(diff, diff);
    }

    return MathF.Sqrt(total);
    }
    }