27#include <unordered_map>
30template <
typename Key,
typename Value>
class Cache {
31 using map_type = std::unordered_map<Key, typename std::add_const_t<Value>>;
41 m_max_size = m_cache.max_size();
52 std::minstd_rand m_rand;
62 void drop_random_element() {
72 std::uniform_int_distribution<size_type>{0,
bucket_count - 1}(m_rand);
74 while (0 == m_cache.bucket_size(
bucket)) {
80 auto const elem_index = std::uniform_int_distribution<size_type>{
81 0, m_cache.bucket_size(
bucket) - 1}(m_rand);
99 bool has(
Key const &k)
const {
return m_cache.contains(k); }
119 if ((m_cache.size() >= m_max_size) && !
has(k)) {
120 drop_random_element();
128 typename map_type::const_iterator
it;
129 std::tie(
it, std::ignore) = m_cache.emplace(k, std::forward<ValueRef>(v));
131 return &(
it->second);
149 template <
typename KeyInputIterator,
typename ValueInputIterator>
159 drop_random_element();
176 auto const needle = m_cache.find(k);
178 if (m_cache.end() !=
needle) {
bool has(Key const &k) const
Query if k is contained in the cache.
void invalidate()
Clear the cache.
typename map_type::size_type size_type
size_type size() const
Number of elements currently cached.
Cache(size_type max_size)
KeyInputIterator put(KeyInputIterator kbegin, KeyInputIterator kend, ValueInputIterator vbegin)
Put a range of values into the cache.
Value const * put(Key const &k, ValueRef &&v)
Put a value into the cache.
Value const * get(Key const &k) const
Get a value.
size_type max_size() const
Maximal size of the cache.
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.