首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#:优化大型数组拷贝

C#:优化大型数组拷贝
EN

Stack Overflow用户
提问于 2016-05-22 11:21:09
回答 3查看 407关注 0票数 1

我需要从一个设备连续填充一个包含16384个双精度元素的数组,该设备提供的数据数组长度为332个元素(这些元素的数据类型为short)。目前,复制需要28ms来填充16384个元素数组。我想让这个至少在10毫秒以下。在下面的代码中,方法getData返回两个由332个元素(iBuf和qBuf)组成的短数组。此方法需要14个刻度(3uS),因此与速度无关。

代码语言:javascript
运行
复制
        getData();

        while (keepGoing)
        {
            for (int i = 0; i < 16384; i++)
            {
                iData[i] = ibuf[rawCounter];
                qData[i] = qbuf[rawCounter];

                rawCounter++;

                if (rawCounter == samplesPerPacket)
                {
                    getData();
                    rawCounter = 0;
                }  

                //processing of data occurs here
            } 

感谢您的帮助和建议

EN

回答 3

Stack Overflow用户

发布于 2016-05-22 15:11:18

使用Array.copy方法可能会对您有所帮助

代码语言:javascript
运行
复制
while(keeping)
{
Array.Copy(ibuf,0,iData,counter,iData.Length)
counter += iData.Length

//Exit while once you hit 16384
//Might also need to check you don't overflow buffer since 16384 doesn't divide evenly into 332.
} 
票数 2
EN

Stack Overflow用户

发布于 2016-05-22 15:00:50

首先,你的代码不会按原样编译。尝试编辑,使你想要做的事情成为最小的例子。您缺少初始化(Java语句),并且看起来像是在用C#编写new代码。

至少使用Array.Copy()。或者,您可以使用指针(如果缓冲区包含内部值),或者像前面提到的复制bytesBlockCopy()。使用sizeof()函数来确定每个元素的字节数。

票数 0
EN

Stack Overflow用户

发布于 2016-07-27 21:11:24

您可以使用以下技术,其中我们利用了处理器是32位(4字节)的事实,在64位处理器上,您只需在方法中将4替换为8。

代码语言:javascript
运行
复制
public static unsafe void CopyUnsafe(byte[] sourceArray, int sourceIndex, byte[] destinationArray, int destinationIndex, int length)
{
    const int procInstrSize = 4; 
    fixed (byte* pDst = &destinationArray[destinationIndex])
    {
        fixed (byte* source = &sourceArray[sourceIndex])
        {
            byte* ps = source;
            byte* pd = pDst;
            // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:
            for (int i = 0; i < length / procInstrSize; i++)
            {
                *((int*) pd) = *((int*) ps);
                pd += procInstrSize;
                ps += procInstrSize;
            }

            // Complete the copy by moving any bytes that weren't moved in blocks of 4:
            for (int i = 0; i < length % procInstrSize; i++)
            {
                *pd = *ps;
                pd++;
                ps++;
            }
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37370206

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档