gpt4 book ai didi

java - 显着优化 for 循环中的字节操作(通过避免循环?)

转载 作者:太空狗 更新时间:2023-10-29 13:57:23 26 4
gpt4 key购买 nike

我必须应用到我的流位操作和算术操作的每个字节。

我将代码示例中的 for 循环确定为输出流的瓶颈,并希望对其进行优化。我只是没有想法 ;)

    private static final long A = 0x1ABCDE361L;
private static final long C = 0x87;
private long x;

//This method belongs to a class that extends java.io.FilteredOutputStream
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; i++) {
x = A * x + C & 0xffffffffffffL;
buffer[offset + i] =
(byte) (buffer[offset + i] ^ (x>>>16));
}

out.write(buffer, offset, length);
}

该代码主要用于 Android 设备。

更新

我希望将执行时间至少缩短 50%。我从我的 CRC32 基准测试中了解到 CRC32#update(byte[] b, int off, int len)CRC32#update(byte b) 快十倍在大于 30 字节的 block 上。 (我的 block 大于 4096 字节)所以,我想我需要一些可以同时处理数组的实现。

最佳答案

下面的代码在 32 位 cpus 上会快一点:

private static final long A = 0x1ABCDE361L;
private static final long C = 0x87;
private long x;

//This method belongs to a class that extends java.io.FilteredOutputStream
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; i++) {
x = A * x + C;
buffer[offset + i] = (byte) (buffer[offset + i] ^ ((int)x>>>16));
}

out.write(buffer, offset, length);
}

由于将 x 右移 16 位并将异或运算结果转换为 byte,实际上只有 16 位到 23 位. 用于 x,因此它可以在右移操作之前转换为 32 位,从而使两个操作在 32 位 cpus 上更快。

关于java - 显着优化 for 循环中的字节操作(通过避免循环?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38392994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com