Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sampling from an array

Tags:

c#

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)

like image 259
Mehdi Souregi Avatar asked Aug 07 '26 11:08

Mehdi Souregi


2 Answers

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];
    }
    
like image 194
DotNet Developer Avatar answered Aug 09 '26 03:08

DotNet Developer


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]);
}
like image 28
Dan Field Avatar answered Aug 09 '26 03:08

Dan Field



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!