0

I have one pointer array of bytes with length(4325376) and i am trying to copy the values of first array to another one,

but the speed of copying is slow even with pointers: ~50ms.

The question is: How to increase the speed of copying?

I know there is a copy function to copy the entire array but i don't know if in my case it's possible to use it.

Here is my code:

var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, SharpDX.Direct3D11.MapFlags.None);
byte[] rgbaValues = new byte[width * height * 4];
var curRowOffs = 0;
var stride = width * 4;

unsafe
{
    byte* srcPtr = (byte *)mapSource.DataPointer;
    Stopwatch sw = Stopwatch.StartNew();
    fixed (byte* pDest = rgbaValues)
    {
        for (uint y = 0; y < height; y++)
        {
            var index2 = curRowOffs;
            var index = y * mapSource.RowPitch;

            for (uint x = 0; x < width; x++)
            {
                pDest[index2] = srcPtr[index + x * 4 + 0];
                pDest[index2 + 1] = srcPtr[index + x * 4 + 1];
                pDest[index2 + 2] = srcPtr[index + x * 4 + 2];
                pDest[index2 + 3] = srcPtr[index + x * 4 + 3];
                index2 += 4;

            }
            curRowOffs += stride;
        }
    }

    sw.Stop();
    Console.WriteLine("{0:N0} Milliseconds", sw.Elapsed.Milliseconds);

}

Udate: The solution was to use Buffer.CopyMemory method, it gave me ~2ms, Awesome!

for (uint y = 0; y < height; y++)
{

    System.Buffer.MemoryCopy(srcPtr, destPtr, width * 4, width * 4);

    srcPtr = &srcPtr[mapSource.RowPitch];
    destPtr = &destPtr[mapDest.Stride];

}
Eamrle
  • 3
  • 1
  • 1
    Is the data shape changing at all (i.e. the underlying data - is it in the same layout in memory) - then have you considered memcpy() or an equivalent - see [a previous solution](https://stackoverflow.com/questions/2996487/memcpy-function-in-c-sharp)? Of course if you aren't changing anything then why copy at all?? – Mr R Mar 10 '21 at 06:26
  • I copy because i want to return the data to the other functions – Eamrle Mar 10 '21 at 08:28
  • You probably only need to copy IF what you've got is only on the stack (so will go out of existance at the end of the method) OR if you want to make sure other methods can't change the original source.. I would guess that's not the case for something coming from from a device. – Mr R Mar 10 '21 at 08:42

0 Answers0