X-Git-Url: https://git.kernel.dk/?p=fio.git;a=blobdiff_plain;f=hash.h;h=d227b938a246881229ab5d5e304427da8f03cff3;hp=93dd8318ffa11dcb4324ab5ec7622880506916fd;hb=029e6147e9005ddb08774193aa8b3a01174007b1;hpb=8e600258bad065fbdfd6a1b2856077d12cd521e5 diff --git a/hash.h b/hash.h index 93dd8318..d227b938 100644 --- a/hash.h +++ b/hash.h @@ -28,13 +28,31 @@ #error Define GOLDEN_RATIO_PRIME for your wordsize. #endif -static inline unsigned long __hash_long(unsigned long val) +/* + * The above primes are actively bad for hashing, since they are + * too sparse. The 32-bit one is mostly ok, the 64-bit one causes + * real problems. Besides, the "prime" part is pointless for the + * multiplicative hash. + * + * Although a random odd number will do, it turns out that the golden + * ratio phi = (sqrt(5)-1)/2, or its negative, has particularly nice + * properties. + * + * These are the negative, (1 - phi) = (phi^2) = (3 - sqrt(5))/2. + * (See Knuth vol 3, section 6.4, exercise 9.) + */ +#define GOLDEN_RATIO_32 0x61C88647 +#define GOLDEN_RATIO_64 0x61C8864680B583EBull + +static inline unsigned long __hash_long(uint64_t val) { - unsigned long hash = val; + uint64_t hash = val; #if BITS_PER_LONG == 64 + hash *= GOLDEN_RATIO_64; +#else /* Sigh, gcc can't optimise this alone like it does for 32 bits. */ - unsigned long n = hash; + uint64_t n = hash; n <<= 18; hash -= n; n <<= 33; @@ -47,9 +65,6 @@ static inline unsigned long __hash_long(unsigned long val) hash += n; n <<= 2; hash += n; -#else - /* On some cpus multiply is faster, on others gcc will do shifts */ - hash *= GOLDEN_RATIO_PRIME; #endif return hash; @@ -60,6 +75,11 @@ static inline unsigned long hash_long(unsigned long val, unsigned int bits) /* High bits are more random, so use them. */ return __hash_long(val) >> (BITS_PER_LONG - bits); } + +static inline uint64_t __hash_u64(uint64_t val) +{ + return val * GOLDEN_RATIO_64; +} static inline unsigned long hash_ptr(void *ptr, unsigned int bits) { @@ -70,7 +90,7 @@ static inline unsigned long hash_ptr(void *ptr, unsigned int bits) * Bob Jenkins jhash */ -#define JHASH_INITVAL GOLDEN_RATIO_PRIME +#define JHASH_INITVAL GOLDEN_RATIO_32 static inline uint32_t rol32(uint32_t word, uint32_t shift) {