26位无符号整数的大数组 [英] Large array of 26-bit unsigned integers

查看:72
本文介绍了26位无符号整数的大数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理RAM中大量的26位变量.使用32位int太昂贵了.访问应尽可能快(尤其是读取操作).

I need to work with a large array of 26-bit variables in RAM. It is too expensive to use 32-bit ints. Access should be as fast as possible (especially read operation).

我采用以下方案:每个26位值分为三个8位值和一个2位值.

I came to the following scheme: each 26-bit value splits to three 8-bit values and one 2-bit value.

#define N 500000000
uint8 arr1[N], arr2[N], arr3[N];
uint8 arr4[N / 4];

int read_value(int index)
{
  int a1 = arr1[index];                                   // bits 0..7
  int a2 = arr2[index];                                   // bits 8..15
  int a3 = arr3[index];                                   // bits 16..23
  int a4 = (arr4[index / 4] >> (2 * (index % 4))) & 3;    // bits 24..25
  return a1 | (a2 << 8) | (a3 << 16) | (a4 << 24);
}

是否有更好的技术来做到这一点? 或者也许有一种很好的方法来处理27/28/29/30位整数?

Is there some better technique to do this? Or maybe there is a nice way to work with 27/28/29/30-bit integers?

推荐答案

当您说使用32位整数太昂贵"时,您是说在空间上明智吗?

When you say it's "too expensive" to use 32-bit ints, do you mean space-wise?

假设您这样做,我不太确定如何在此为您提供帮助.但是,就读取速度而言,C/C ++中的数组为您提供了对数组元素的恒定访问时间(这是假设内存已经在CPU高速缓存中;如果不是,它将需要更长).因此,读取元素0花费的时间与读取元素10,000相同;您所拥有的代码可能会使速度变慢,但是我不能肯定地说.

Assuming that you do, I'm not really sure how to help you there. However, in terms of read speed, an array in C/C++ provides you constant-time access to the elements of the array(this is assuming that the memory is already in the CPU cache; if it isn't, it's going to take longer). Therefore, reading element 0 takes the same amount of time as reading element 10,000; the code that you have might make this slower, but I can't say that for certain.

虽然这段代码看起来应该可以执行您想要的操作,但是简单地做一个int数组可能是最有意义的,即使它会占用更多空间.如果绝对需要这样做,可以尝试将inline放入方法声明中,以便编译器可以在每次使用它时对其进行扩展.

While it looks like this code should do what you want to do, it would probably make the most sense to simply do an array of ints, even though it would take up more space. If you absolutely have to this, you could try putting inline in your method declaration so the compiler can expand it whenever you use it.

这篇关于26位无符号整数的大数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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