优化求和2个字节数组的总和 [英] Optimize summing 2 arrays of bytes

查看:92
本文介绍了优化求和2个字节数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历一个字节数组,并在for循环中添加另一个字节数组的值。

I am iterating through an array of bytes and add values of another array of bytes in a for loop.

        var random = new Random();
        byte[] bytes = new byte[20_000_000]; 
        byte[] bytes2 = new byte[20_000_000];

        for (int i = 0; i < bytes.Length; i++)
        {
            bytes[i] = (byte)random.Next(255);
        }

        for (int i = 0; i < bytes.Length; i++)
        {
            bytes2[i] = (byte)random.Next(255);
        }

        //how to optimize the part below
        for (int i = 0; i < bytes.Length; i++)
        {
            bytes[i] += bytes2[i];
        }

是否有任何方法可以加快该过程,因此它可以比

Is there any way to speed up the process, so it can be faster than linear.

推荐答案

您可以使用 Vector

static void Add(Span<byte> dst, ReadOnlySpan<byte> src)
{
    Span<Vector<byte>> dstVec = MemoryMarshal.Cast<byte, Vector<byte>>(dst);
    ReadOnlySpan<Vector<byte>> srcVec = MemoryMarshal.Cast<byte, Vector<byte>>(src);

    for (int i = 0; i < dstVec.Length; ++i)
    {
        dstVec[i] += srcVec[i];
    }

    for (int i = dstVec.Length * Vector<byte>.Count; i < dst.Length; ++i)
    {
        dst[i] += src[i];
    }
}

如果在此处使用指针将走得更快对齐其中一个数组。

Will go even faster if you use a pointer here to align one of your arrays.

这篇关于优化求和2个字节数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆