【问题标题】:Count number of rehashing in unordered map计算 unordered_map 中的重新散列次数
【发布时间】:2017-07-18 14:38:29
【问题描述】:

评估 unordered_map 性能的正确方法是什么? [C++14]

在我的代码中,我非常广泛地使用了 std::unordered_map,大约有数十亿个键。出于性能的目的,我希望知道 unordered_map 的行为,它必须重新散列多少次以及所有其他参数(多少个桶?在重新散列之前有多少个桶是空的?)。我知道 stl 提供了桶的数量。但是还需要什么来分析或者你用什么来分析?

【问题讨论】:

  • “我知道 stl 提供了桶的数量?” 悲伤但真实。桶接口不应该存在。 :(

标签: c++ c++11 c++14


【解决方案1】:

与许多标准容器一样,unordered_map 的大小必须呈指数增长。确切的费率由实施定义;您可以检查您的实现规范或其源代码。

它如何调整大小是确定性的。如果你将它包裹在一个 shim 中,你可以通过在每个允许增长容器的操作之前和之后检查 bucket_count 来检测这些调整大小。

您可以遍历存储桶:

template<class UnorderedMeow>
std::size_t empty_buckets( UnorderedMeow&& meow ) {
  std::size_t r = 0;
  auto buckets = meow.buckets_count();
  for (decltype(buckets) i = 0; i < buckets; ++i)
    if (meow.bucket_size(i)==0)
      ++r;
  return r;
}

找出有多少是空的。

如果您使用基于继承的组合并仅覆盖您知道可以添加/删除内容的组合...

template<class Base>
struct instrumented_unordered_map:Base {
  using Self = instrumented_unordered_map;
  using Base::Base;
  using key_type = Base::key_type; // etc
  struct instrument {
    Self* self;
    instrument( Self* s ):self(s) {
      self->start_instrument();
    }
    ~instrument() {
      self->end_instrument();
    }
  };
  struct instrument_state {
    // blah
  };
  instrument_state state;
  void start_instrument() {
    // populate state
  }
  void end_instrument() {
    // extract from state, generate report
  }
  decltype(auto) operator[]( key_type const& key ) {
    instrument _(this);
    return Base::operator[](key);
  }
  // etc  
};

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 2017-03-19
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2015-09-14
    • 1970-01-01
    相关资源
    最近更新 更多