我可以使用与其他类型的值/对象相同的字节吗?

时间:2015-10-04 18:02:07

标签: c# performance unit-testing data-structures unsafe

我的目标是执行 List<T> 我正在测试数组,发现几个起点没有进行测试 我试图在屏幕上捕获位图之前测试过这个, 并且测试证明使用就足够了。 我的问题是除了byte []

之外,哪些数据类型可以使用此Copy()代码

说我希望数据存储单元能够利用非托管/不安全的优势

        public unsafe struct NusT
        {
            public unsafe int vi;
            public unsafe bool vb;
        }

而不是填充列表

我按如下方式初始化结构:1)

NusT n; 
n.vi= 90;
n.vb=true

我在测试完之后测试了这个:2)

NusT n = new NusT(){vi=90, vb=true};

此测试经过测试:3)

NusT n = new NusT("90", true);

我认为最后两个都有相同的结果,但第一个是快速的,因为我没有创建一个对象所以

NusT n-> instructions- 1
n.vi=90 -> instructions- 1
n.vb=true -> instructions- 1 

现在我把我能做的最小化了,这开始于课程的开头: 婊子甚至比2&amp;以上3,因为它也使用属性

class bigAndSlow
{
     public int a { get; private set;}
     public bool b { get; private set;}
     public string  c { get; private set;}

     public bigAndSlow(int .. ,boo .. , string.. )
     {
        initialise ...
     }
}

所以现在最后的决定是

        public unsafe struct NusT
        {
            public unsafe int vi;
            public unsafe bool vb;
        }

我如何实现这个超快的数据单元来使用

上的Copy()
NusT[] NustyArr;


    static unsafe void Copy(byte[] src, int srcIndex,
            byte[] dst, int dstIndex, int count)
        {
            if (src == null || srcIndex < 0 ||
                dst == null || dstIndex < 0 || count < 0)
            {
                throw new ArgumentException();
            }
            int srcLen = src.Length;
            int dstLen = dst.Length;
            if (srcLen - srcIndex < count ||
                dstLen - dstIndex < count)
            {
                throw new ArgumentException();
            }


            // The following fixed statement pins the location of
            // the src and dst objects in memory so that they will
            // not be moved by garbage collection.          
            fixed (byte* pSrc = src, pDst = dst)
            {
                byte* ps = pSrc;
                byte* pd = pDst;

                // Loop over the count in blocks of 4 bytes, copying an
                // integer (4 bytes) at a time:
                for (int n = 0; n < count / 4; n++)
                {
                    *((int*)pd) = *((int*)ps);
                    pd += 4;
                    ps += 4;
                }

                // Complete the copy by moving any bytes that weren't
                // moved in blocks of 4:
                for (int n = 0; n < count % 4; n++)
                {
                    *pd = *ps;
                    pd++;
                    ps++;
                }
            }
        }


        static void Main(string[] args)
        {
            byte[] a = new byte[100];
            byte[] b = new byte[100];
            for (int i = 0; i < 100; ++i)
                a[i] = (byte)i;
            Copy(a, 0, b, 0, 100);
            Console.WriteLine("The first 10 elements are:");
            for (int i = 0; i < 10; ++i)
                Console.Write(b[i] + " ");
            Console.WriteLine("\n");
        }

1 个答案:

答案 0 :(得分:2)

是的,您可以使用任何 blittable 类型执行此操作。 blittable类型是基本类型(整数和浮点类型,但不是bool),blittable类型的一维数组和仅包含blittable类型字段的结构。

结构NusT不是blittable,因为它包含bool字段。只需将其更改为byte,您将获得一个可以获取指针的blittable结构。

以下是适用于任何类型的代码:

static unsafe void UnsafeCopy<T>(T[] src, int srcIndex, T[] dst, int dstIndex, int count) where T : struct
{
    if (src == null || srcIndex < 0 || dst == null || dstIndex < 0 || count < 0 || srcIndex + count > src.Length || dstIndex + count > dst.Length)
    {
        throw new ArgumentException();
    }

    int elem_size = Marshal.SizeOf(typeof(T));

    GCHandle gch1 = GCHandle.Alloc(src, GCHandleType.Pinned);
    GCHandle gch2 = GCHandle.Alloc(dst, GCHandleType.Pinned);

    byte* ps = (byte*)gch1.AddrOfPinnedObject().ToPointer() + srcIndex * elem_size;
    byte* pd = (byte*)gch2.AddrOfPinnedObject().ToPointer() + dstIndex * elem_size;
    int len = count * elem_size;

    try
    {
        // Loop over the count in blocks of 4 bytes, copying an
        // integer (4 bytes) at a time:
        for (int n = 0; n < len / 4; n++)
        {
            *((int*)pd) = *((int*)ps);
            pd += 4;
            ps += 4;
        }

        // Complete the copy by moving any bytes that weren't
        // moved in blocks of 4:
        for (int n = 0; n < len % 4; n++)
        {
            *pd = *ps;
            pd++;
            ps++;
        }
    }
    finally
    {
        gch1.Free();
        gch2.Free();
    }
}

但我强烈建议您使用Array.Copy。它已经是复制数组的最有效方法。请参阅下面复制1M元素数组的基准:

  

byte [] Array.Copy:57,491 us

     

byte [] FastCopy:138,198 us

     

byte [] JustCopy:792,399 us

     

byte [] UnsafeCopy:138,575 us

     

byte [] MemCpy:57,667 us

     

NusT [] Array.Copy:1,197 ms

     

NusT [] JustCopy:1,843 ms

     

NusT [] UnsafeCopy:1,550 ms

     

NusT [] MemCpy:1,208 ms

FastCopy是您的复制功能,UnsafeCopy是我的模板化功能,JustCopy是一个简单的实现for (int i = 0; i < src.Length; i++) dst[i] = src[i];MemCpy是对msvcrt memcpy函数的PInvoke调用。

判决结果是:在C#中使用指针来提高性能是一种不好的做法。 JIT不优化不安全的代码。最佳解决方案是将性能关键代码移动到本机DLL。