同一台机器,都是VS2013,都是Debug版。 复制10M 内存5000次,C++ 4秒,C#6秒。C++稍快,除非核心模块没必要C#换C++。下面是C++和C#的测试代码。

  [TestMethod]
    public void MemcpyUseTime()
    {
        
        byte[] src = Enumerable.Repeat((byte)0x08, 1000*1000*10).ToArray();
        src[0] = 5;
        src[10000] = 6;
        IntPtr ptr = Marshal.AllocHGlobal(src.Length);

        for (int i = 0; i < 5000; i++)
        {
            Marshal.Copy(src, 0, ptr, src.Length);
        }

        unsafe { 
        byte* pb = (byte*)ptr;
        Assert.AreEqual(5, pb[0]);
        Assert.AreEqual(6, pb[10000]);
        }
    }

TEST_METHOD(TestMethod1)
        {
            const int iNum = 1000 * 1000 * 10;
            char* p = new char[iNum];
            memset(p, iNum, 0);
            p[0] = 5;
            p[10000] = 6;

            char* p2 = new char[iNum];
            for (int i = 0; i < 5000; i++)
            {
                memcpy(p2, p, iNum);
            }
            

            Assert::AreEqual((char)5 , p2[0]);
            Assert::AreEqual((char)6, p2[10000]);
        }

posted on 2023-04-27 11:29  闻缺陷则喜何志丹  阅读(8)  评论(0编辑  收藏  举报  来源