Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vectorize time-series indicators #1260

Open
DaveSkender opened this issue Oct 10, 2024 · 1 comment
Open

Vectorize time-series indicators #1260

DaveSkender opened this issue Oct 10, 2024 · 1 comment
Milestone

Comments

@DaveSkender
Copy link
Owner

Consider implementing time-series vector method (reverted due to minor floating-point related test errors, from diff of parallel calculations)

...
double sum = 0;
int start = i - lookbackPeriods + 1;
int end = i + 1;

// SIMD optimization
int vectorSize = Vector<double>.Count;
int simdEnd = start + ((end - start) / vectorSize * vectorSize);

for (int p = start; p < simdEnd; p += vectorSize)
{
    Vector<double> vector = new(values, p);
    sum += Vector.Sum(vector);
}

for (int p = simdEnd; p < end; p++)
{
    sum += values[p];
}

sma = sum / lookbackPeriods;
...

Note

.NET blogs say this is 10x faster and more stable in the upcoming .NET 9 release (November)

Originally posted by @DaveSkender in #1230 (comment)

@DaveSkender
Copy link
Owner Author

DaveSkender commented Jan 30, 2025

Also consider FMA, but requires minimum.NET 7 targeting for better outcomes

using System.Numerics;

public static float DotProductFMA(float[] a, float[] b)
{
    var sum = new Vector<float>(0);
    int i = 0;
    
    for (; i <= a.Length - Vector<float>.Count; i += Vector<float>.Count)
    {
        sum = Vector<float>.FusedMultiplyAdd(new Vector<float>(a, i), new Vector<float>(b, i), sum);
    }

    float result = Vector.Sum(sum);

    for (; i < a.Length; i++) 
    {
        result += a[i] * b[i];
    }

    return result;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Development

No branches or pull requests

1 participant