C# unsafe 快速复制数组

(1)

     /// <summary>
     /// 复制内存
     /// </summary>
     /// <param name="dest">目标指针位置</param>
     /// <param name="src">源指针位置</param>
     /// <param name="count">字节长度</param>
     /// <returns></returns>
     [DllImport("msvcrt.dll")]
     public static extern IntPtr memcpy(IntPtr dest, IntPtr src, int count);
     unsafe static int[] MyCopy(int[] oriInts)
     {
         int[] result = new int[oriInts.Length];
         int lenth= oriInts.Length;
         fixed (int* pOri= oriInts) //fixed语句获取指向任意值类型、任意值类型数组或字符串的指针
         {
             fixed (int* pResult = result)
             {
                 memcpy(new IntPtr(pResult), new IntPtr(pOri), sizeof(int) * lenth);//注意,第一个参数和第二个参数的顺序
             }
         }
         return result;
     }
     static int[] MyCopyB(int[] oriInts)
     {
         int[] result = new int[oriInts.Length];
         for(int i=0;i<oriInts.Length;i++)
         {
             result[i]= oriInts[i];
         }
         return result;
     }

 static void Main(string[] args)
 {
     var a = sizeof(int);
     int[] ori = new int[100000000];
     for(int i = 0; i < ori.Length; i++)
     {
         ori[i] = i;
     }
     Stopwatch sw = new Stopwatch();
     sw.Start();
     int[] copyA= MyCopy(ori);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
     sw.Restart();
     int[] copyB = MyCopyB(ori);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
}

(2)

static unsafe void MyCopy(double[] source, float[]target,int targetOffset,int count)
{
    fixed(double* sourcePtr = source)
    {
        fixed(float* targetPtr = target)
        {
            float* targetStPtr = targetPtr + targetOffset;
            double* sourceEndPtr = sourcePtr + count;
            for(double* iPtr = sourcePtr; iPtr != sourceEndPtr; iPtr+=1)
            {
                *targetStPtr = (float)*iPtr;
                targetStPtr += 1;
            }
        }
    }
}

static void MyCopyB(double[] source, float[] target,int targetOffset,int count)
{
    for(int i = 0; i < count; i++)
    {
        target[targetOffset + i] = (float)source[i];
    }
}

 static void Main(string[] args)
 {
     double[] ori = new double[10000000];
     for(int i = 0; i < ori.Length; i++)
     {
         ori[i] = i + 2;
     }
     Stopwatch sw = new Stopwatch();
     float[] copyA = new float[ori.Length];
     float[] copyB = new float[ori.Length];

     sw.Start();
     MyCopy(ori,copyA,0,ori.Length);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
     sw.Restart();
     MyCopyB(ori,copyB,0,ori.Length);
     sw.Stop();
     Console.WriteLine(sw.ElapsedMilliseconds);
}


可见第一个基于指针的复制,非常的快。

posted @ 2024-10-11 23:49  JohnYang819  阅读(5)  评论(0编辑  收藏  举报