簡體   English   中英

基本結構的哈希函數

[英]Hash function for basic struct

我有一個非常簡單的 POD 結構,里面有 3 個短褲,我計划在unordered_set使用它數億次。

這是我目前正在做的事情:

struct ps3 {
    short v1;
    short v2;
    short v3;

    bool operator==(const ps3& other) const {
        return v1 == other.v1
            && v2 == other.v2
            && v3 == other.v3;
    }
}

// Hash function:
size_t operator()(const ps3& p) const {
    return (static_cast<size_t>(*reinterpret_cast<const int*>(&p)) << 16) | p.v3;
}

哈希函數只返回ps3的值,因為它可以容納 8 個字節。

(我在這里看到,對於基本類型,標准散列函數只返回自身,所以如果它是一個值為 30 的int ,它將返回一個 30 的散列)

我通過獲取前四個字節返回ps3的值,移位 16,然后對最后一個 short 進行OR

我想知道這種方法是否好,是否有什么我可以做的來提高性能(因為它被使用了數億次,可能是數十億次)

基准

我做了一些基准測試,這是我發現的:

  • 當前方法:1076ms
  • memcpy:1500 毫秒
  • 按照@rturrado 的建議使用hash<short>()組合每個 short:876ms

根據 A Tour of C++ 的評論,您自己的哈希的可能實現是:

struct ps3 { short v1; short v2; short v3; };

struct ps3_hash {
    size_t operator()(const ps3& other) const {
        return hash<short>()(other.v1) ^ hash<short>()(other.v2) ^ hash<short>()(other.v3);
    }
};

unordered_set<ps3, ps3_hash> my_set;  // set of ps3s using ps3_hash for lookup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM