【发布时间】:2010-11-06 09:32:22
【问题描述】:
由于内存限制,我必须将一些值对存储在一个 6 位/对(3 位/值)的数组中。当我想根据该对的索引将该数组作为普通数组访问时,问题就来了。 数组是这样的
|--byte 0 | --byte 1 | --byte 2
|00000011 | 11112222 | 22333333 ... and so on, the pattern repeats.
|------|-------|--------|------|
pair 0 pair 1 pair 2 pair 3
=> 4 pairs / 3 bytes
您可以看到,有时(对于可被 1 和 2 整除的索引)提取值需要 2 个字节。
我创建了一个给定索引的函数,返回该对中的第一个值(3 位)和另一个(也是 3 位)。
void GetPair(char *array, int index, int &value1, int &value2) {
int groupIndex = index >> 2; // Divide by 4 to get the index of the group of 3 bytes (with 4 pairs)
// We use 16 bits starting with the first byte from the group for indexes divisible by 0 and 1,
// 16 bits starting with the second byte when divisible by 2 and 3
short int value = *(short int *)(array + groupIndex + ((index & 0x02) >> 1));
switch(index & 0x03) { // index % 4
case 0: {
// extract first 3 bits
value1 = (value & 0xE000) >> 13;
// extract the next 3 bits
value2 = (value & 0x1C00) >> 10;
break;
}
case 1: {
value1 = (value & 0x380) >> 7;
value2 = (value & 0x70) >> 4;
break;
}
case 2: {
value1 = (value & 0xE00) >> 9;
value2 = (value & 0x1C0) >> 6;
break;
}
case 3: {
value1 = (value & 0x38) >> 2;
value2 = value & 0x7;
break;
}
}
现在我的问题是:有没有更快的方法来提取这些值?
我做了一个测试,当使用 2 个字节/对(1 个字节/值)时,访问所有对(总共 53 个)大约需要 6 秒 1 亿次。使用紧凑数组时,大约需要 22 秒 :((可能是因为它需要计算所有这些掩码和位移)。
我试图尽可能清楚地解释......如果没有,请原谅我。
【问题讨论】:
标签: c++ optimization memory