SciSharp / NumSharp

High Performance Computation for N-D Tensors in .NET, similar API to NumPy.
https://github.com/SciSharp
Apache License 2.0
1.34k stars 188 forks source link

NumSharp is slower than normal for loop ?!? #444

Closed minhduc66532 closed 3 years ago

minhduc66532 commented 3 years ago
static void Main(string[] args)
{
    List<double> test2 = new();
    Random randNum = new Random();
    for (int i = 0; i < 1000000; i++)
    {
        test2.Add(randNum.NextDouble());
    }
    double[] ar = test2.ToArray();
    NDArray arn = new NDArray(ar);
    Stopwatch s = new();

    int count = 0;
    while (count < 5)
    {
        count++;

        double avg = 0;
        s.Start();
        for (int i = 0; i < ar.Length; i++)
        {
            avg += ar[i];
        }
        avg /= ar.Length;
        s.Stop();
        Console.WriteLine($"{s.ElapsedMilliseconds} {s.ElapsedTicks}");
        s.Reset();

        s.Start();
        arn.mean();
        s.Stop();
        Console.WriteLine($"{s.ElapsedMilliseconds} {s.ElapsedTicks}");
        s.Reset();
        Console.WriteLine();
    }
}

The result: image Am I doing anything wrong because from the test result NumSharp is 3 times slower than normal for loop

Nucs commented 3 years ago

It is due to usage of Parallel.For internally by our DefaultEngine, we are considering to remove this feature in favor of regular tight for-loop by default where Parallel.For will be exposed via ParallelEngine that can be assigned to any NDArray. Any performance impact beyond that is the overhead of creating the NDArray, allocating the memory and handling dtype and shape behind the scenes.

minhduc66532 commented 3 years ago

Ohh ok, so more improvements coming soon I guess. Thank you for the answer