Mehdi Souregi
Mehdi Souregi

Reputation: 3265

Sampling from an array

I have a float array containing 1M floats

I want to do sampling: for each 4 floats I want to take only 1. So i am doing this :

for(int i = 0; i< floatArray.Length; i++) {
    if(i % 4 == 0) {
         resultFloat.Add(floatArray[i])
    }
}

This works fine, but it takes much time to run through all the elements , is there any other methods to make it with better results (if there are any)

Upvotes: 2

Views: 773

Answers (5)

Camilo Terevinto
Camilo Terevinto

Reputation: 32088

Just to add another option, if you want this to be the fastest, use Parallel.For instead of a normal for loop.

int resultLength = (floatArray.Length + 3) / 4;
var resultFloat = new float[resultLength];

Parallel.For(0, resultLength, i =>
{
    resultFloat[i] = floatArray[i * 4];
});

Upvotes: 0

Thomas Hilbert
Thomas Hilbert

Reputation: 3629

If you really have an issue with performance, then you'd be even better off not using a dynamic container for the results, but a statically sized array.

float[] resultFloat = new float[(floatArray.Length + 3) >> 2];
for(int i = 0; i < resultFloat.Length; i++)
    resultFloat[i] = floatArray[i << 2];

Usually performance isn't an issue thow, and you shouldn't optimize until a profiler gave you proof that you should. In all other cases the more readable code is preferrable.

Upvotes: 1

DotNet Developer
DotNet Developer

Reputation: 3018

I can see two factors that might be slowing down performance.

  1. As you have already been offered, you should set the step to 4:

    for (int i = 0; i < floatArray.Length; i += 4)
    {
        resultFloat.Add(floatArray[i]);
    }
    
  2. Looks like resultFloat is a list of float. I suggest to use array instead of list, like this:

    int m = (floatArray.Length + 3) / 4;
    
    float[] resultFloat = new float[m];
    
    for (int i = 0, k = 0; i < floatArray.Length; i += 4, k++)
    {
        resultFloat[k] = floatArray[i];
    }
    

Upvotes: 7

Kaustav Halder
Kaustav Halder

Reputation: 15

List<decimal> list = new List<decimal>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
list.Add(9);
list.Add(10);
list.Add(11);
list.Add(12);
list.Add(13);
list.Add(14);
list.Add(15);
list.Add(16);

var sampleData = list.Where((x, i) => (i + 1) % (4) == 0).ToList();

Upvotes: -3

Dan Field
Dan Field

Reputation: 21661

Just increment your loop by 4 each iteration instead of by 1:

for(int i = 0; i< floatArray.Length; i+=4)
{
    resultFloat.Add(floatArray[i]);
}

Upvotes: 6

Related Questions