linux golden_ratio_prime 64,hash算法

简单一点的hash算法就是直接取模。

高级一点的hash算法会乘以一个大素数来将源数据的分布规律变得不那么显著,也就是说,不管输入的是一串分布很紧凑的数字序列还是很稀疏的数字序列,生成的结果都是非常分散的数字序列。

linux内核代码里面的这个hash要更高一级,包含2个特征,最接近32位或者者64位上限黄金分割点的素数,只要要最少的移位和求和就能生成。

前者确保即便是1,2这样的小数也会被乘溢出,被轻易打散。

后者确保任何一个整数乘这个大素数的时候都可以通过最少的移位和求和就可得到乘积,不用傻傻的真的相乘。

/* 2^31 + 2^29 - 2^25 + 2^22 - 2^19 - 2^16 + 1 */

#define GOLDEN_RATIO_PRIME_32 0x9e370001UL

/*  2^63 + 2^61 - 2^57 + 2^54 - 2^51 - 2^18 + 1 */

#define GOLDEN_RATIO_PRIME_64 0x9e37fffffffc0001UL

#if BITS_PER_LONG == 32

#define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_32

#define hash_long(val, bits) hash_32(val, bits)

#elif BITS_PER_LONG == 64

#define hash_long(val, bits) hash_64(val, bits)

#define GOLDEN_RATIO_PRIME GOLDEN_RATIO_PRIME_64

#else

#error Wordsize not 32 or 64

#endif

static inline u64 hash_64(u64 val, unsigned int bits)

{

u64 hash = val;

/*  Sigh, gcc can't optimise this alone like it does for 32 bits. */

u64 n = hash;

n <<= 18;

hash -= n;

n <<= 33;

hash -= n;

n <<= 3;

hash += n;

n <<= 3;

hash -= n;

n <<= 4;

hash += n;

n <<= 2;

hash += n;

/* High bits are more random, so use them. */

return hash >> (64 - bits);

}

static inline u32 hash_32(u32 val, unsigned int bits)

{

/* On some cpus multiply is faster, on others gcc will do shifts */

u32 hash = val * GOLDEN_RATIO_PRIME_32;

/* High bits are more random, so use them. */

return hash >> (32 - bits);

}

static inline unsigned long hash_ptr(const void *ptr, unsigned int bits)

{

return hash_long((unsigned long)ptr, bits);

}

#endif /* _LINUX_HASH_H */

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值