1

I need to convert the following 1D array of my class Frames to a 2D byte array (I need the 2D byte array for sending to a GPU, I cannot use jagged arrays, Lists, or other enumerables).

Right now, my conversion is very slow and stupid:

public byte[,] allBytes()
{
    byte[,] output = new byte[this.frameListSize, this.ySize * this.xSize];
    for (int y = 0; y < this.frameListSize; y++)
    {
        byte[] bits = this.frameList[y].getBytes();
        for (int x = 0; x < this.ySize * this.xSize; x++)
        {
            output[y, x] = bits[x];
        }
    }
    return output;
}

The snippets that define of frameList and Frame are below:

public Frame[] frameList;

public class Frame
{

  public byte[] bits;

  public byte[] getBytes()
  {
    return bits;
  }
}

1 Answer 1

2

If you use .NET Framework 4 or higher, you can use Parallel (for a first speeding up)

    public byte[,] allBytes()
    {
        int size1 = this.frameListSize;
        int size2 = this.ySize * this.xSize;
        byte[,] output = new byte[size1, size2];
        Parallel.For(0, size1, (y) =>
        {
            byte[] bits = this.frameList[y].getBytes();
            System.Buffer.BlockCopy(bits, 0, output, 0 + size2 * y, bits.Length);
        });
        return output;
    }

Buffer.BlockCopy is about 20 times faster than normal copying. Make sure bits.Length has the same value as size2. Otherwise you can run into errors

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I am using .net 4.5.2, But I think the CPU usage is hurting my video frame grabber which is what is deliving all these bytes (I am getting buffer overflows when I do this in parallel with the fetching of the data). The resultant 2D byte array is [21, 1024x1024]
from the MSDN documentation you quote: ArgumentException The current Array does not have exactly one dimension.
Im sorry, its my fault. Then you have to use Block.Copy (changed in my answer)
That's a dramatic improvement. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.