ste*_*km3 3 c++ optimization hash multithreading std
我有一张包裹在锁中的无序地图。
多个线程正在查找,插入。因此需要锁。
我的问题是,我不希望在无序映射代码中完成哈希计算,因为该哈希函数确实需要时间,因此在该时间不必要地保持了锁定。
我的想法是让调用者在锁之外计算哈希,然后在查找,插入期间将其传递到无序映射中。
使用标准无序地图可以吗?
您可以预先计算哈希并将其存储在密钥中,然后在地图的互斥锁锁定时使用自定义哈希函数来检索哈希:
#include <iostream>
#include <unordered_map>
#include <string>
#include <utility>
struct custom_key
{
custom_key(std::string s)
: data(std::move(s))
, hash_value(compute_hash(data))
{}
const std::string data;
static std::size_t compute_hash(const std::string& dat) {
return std::hash<std::string>()(dat);
}
// pre-computed hash
const std::size_t hash_value;
};
bool operator==(const custom_key& l, const custom_key& r) {
return l.data == r.data;
}
namespace std {
template<> struct hash<custom_key> {
using argument_type = custom_key;
using result_type = size_t;
result_type operator()(const argument_type& k) const {
return k.hash_value;
}
};
}
using namespace std;
auto main() -> int
{
unordered_map<custom_key, std::string> m;
m.emplace(custom_key("k1"s), "Hello, World");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
更新:
自从审查了这个答案以来,我发现我们可以做得更好:
#include <iostream>
#include <unordered_map>
#include <string>
#include <utility>
/* the precompute key type */
template<class Type>
struct precompute_key {
/* may be constructed with any of the constructors of the underlying type */
template<class...Args>
precompute_key(Args &&...args)
: value_(std::forward<Args>(args)...), hash_(std::hash<Type>()(value_)) {}
operator Type &() { return value_; }
operator Type const &() const { return value_; }
auto hash_value() const { return hash_; }
auto value() const { return value_; }
auto value() { return value_; }
private:
Type value_;
std::size_t hash_;
};
template<class Type>
bool operator==(const precompute_key<Type> &l, const precompute_key<Type> &r) {
return l.value() == r.value();
}
namespace std {
template<class Type>
struct hash<precompute_key<Type>> {
auto operator()(precompute_key<Type> const &arg) const {
return arg.hash_value();
}
};
}
auto main() -> int {
std::unordered_map<precompute_key<std::string>, std::string> m;
m.emplace("k1", "Hello, World");
return 0;
}
Run Code Online (Sandbox Code Playgroud)