linux kernel 的hash散列函數 : hash_long

來源:互聯網
上載者:User

教課數上的hash函數一般都是對模數取餘,模數一般就是hash表的長度(桶的個數),通常為了較好的散列性,還把模數調整為一個質數.

那麼核心中的hash函數是什麼樣呢?

以儲存pid的hash表的hash函數 hash_long為例, 隨便測試下其散列的隨機性.

測試代碼:

#include <stdio.h>#include <stdlib.h>#include <time.h>unsigned long hash_long(unsigned long val, unsigned int bits) {     unsigned long hash = val * 0x9e370001UL;     return hash >> (32 - bits); }int main(){    // 假設hash table的長度為8(2^3)    int bits = 3;    int elem_num = 1<<bits;    int vec[elem_num];                                                                                                                                        for (int i=0; i<elem_num; ++i)        vec[i] = 0;    srand(time(NULL));    for(int i=0; i<1000; i++)    {           int num = rand();        //printf("num:%d\n", num);        int elem_idx = hash_long(num, bits);        vec[elem_idx] ++;     }       printf("========================\n");    for (int i=0; i<elem_num; ++i)    {           printf("vec[%d]: %d\n", i, vec[i]);    }       return 0;}

輸出結果:

看上去還不錯, 不同的桶中的元素個數差不多.

vec[0]: 116vec[1]: 142vec[2]: 112vec[3]: 134vec[4]: 129vec[5]: 124vec[6]: 118vec[7]: 125

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.