我正在尝试编写一个绽放过滤器,存储大约80,000个字符串...现在我猜测每个字符串可以是2个字长。要存储80,000个字符串..我需要80,000 * 2 = 16kBytes?
如果我必须存储16kB = 16 * 1000 * 8 = 128,000bits,我需要一个至少2 ^ 17 = 131,072的位图。这就是我现在所拥有的
int main(){
char *str = "hello world";
int c = sizeof(unsigned char);
/*
* declare the bit array
*/
unsigned char bit_arr[128000/c];
/*
* couple of hash functions
*/
unsigned int bkd = bkdrhash(str, strlen(str));
unsigned int rsh = rshash(str, strlen(str));
unsigned int jsh = jshash(str, strlen(str));
/*
* logic to set bit
* Access the bitmap arr element
* And then set the required bits in that element
*/
bit_arr[bkd/c] & (1 << (bkd%c));
bit_arr[rsh/c] & (1 << (rsh%c));
bit_arr[jsh/c] & (1 << (jsh %c));
}
有更好/最佳的方法吗?
感谢
答案 0 :(得分:4)
你的数学已关闭。 80k * 2 = 160K。仍然如克里斯多德所说,这些在普通台式机甚至是智能手机上相当小。如果您的应用程序是嵌入式的,或者您有其他大型分配,那么它可能是一个不同的故事。 iPhone默认情况下为1兆字节堆栈,辅助线程为1/2兆字节。
在总线为N位宽的机器上,使用N位宽的整数可能具有明显的优势。如此抽象远离单词大小:
#define WORD_BYTES 4
#define BYTE_BITS 8
#define WORD_BITS (BYTE_BITS * WORD_BYTES)
#define BITSET_BITS (1u << 17)
#define BITSET_WORDS (BITSET_BITS / WORD_BITS)
typedef unsigned int WORD;
typedef WORD BITSET[BITSET_WORDS];
typedef WORD *BITSET_REF;
#define bit(N) (1u << (N))
/* Allocate a bitset on the heap and return a reference to it. */
BITSET_REF new_bitset(void)
{
return safe_malloc(sizeof(BITSET));
}
/* Arrange for these functions to be inlined by the compiler rather
than using fancy macros or open coding. It will be better in
the long run. */
int is_set(BITSET_REF bitset, int n)
{
return (bitset[n / WORD_BITS] | bit(n % WORD_BITS)) != 0;
}
void set(BITSET_REF bitset, int n)
{
bitset[n / WORD_BITS] |= bit(n % WORD_BITS);
}
void clear(BITSET_REF bitset, int n)
{
bitset[n / WORD_BITS] &= ~bit(n % WORD_BITS);
}
答案 1 :(得分:1)
除了各种明显的拼写错误之外,在堆栈上分配大型数组(作为局部变量)通常是一个坏主意。堆栈默认不是很大(通常只有大约8MB左右),虽然你可以重新配置东西以获得更大的堆栈,但通常在堆上分配大对象或使用静态分配要好得多。
那就是说,128K绝对不是'巨大的'。通过许多措施,它甚至不是“大”。关于它唯一可以说的是它不是'小'