Commit ea716d65 authored by Martin Reinecke's avatar Martin Reinecke

Merge branch 'lru_cache' into 'new_interface'

LRU cache eviction policy

See merge request !11
parents 5663a609 45cf4ef0
......@@ -41,6 +41,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#error This file requires at least C++11 support.
#endif
#include <array>
#include <cmath>
#include <cstring>
#include <cstdlib>
......@@ -2266,23 +2267,44 @@ template<typename T0> class pocketfft_r
template<typename T> shared_ptr<T> get_plan(size_t length)
{
constexpr size_t nmax=10;
static vector<shared_ptr<T>> cache(nmax);
static size_t lastpos=0;
static array<shared_ptr<T>, nmax> cache;
static array<size_t, nmax> last_access{{0}};
static size_t access_counter = 0;
static mutex mut;
auto find_in_cache = [&]() -> shared_ptr<T>
{
for (size_t i=0; i<nmax; ++i)
if (cache[i] && (cache[i]->length()==length))
{
last_access[i] = access_counter++;
// Guard against overflow
if (access_counter == 0)
last_access.fill(0);
return cache[i];
}
return nullptr;
};
{
lock_guard<mutex> lock(mut);
for (size_t i=0; i<nmax; ++i)
if (cache[i] && (cache[i]->length()==length))
return cache[i];
auto p = find_in_cache();
if (p) return p;
}
auto plan = make_shared<T>(length);
{
lock_guard<mutex> lock(mut);
for (size_t i=0; i<nmax; ++i)
if (cache[i] && (cache[i]->length()==length))
return cache[i];
cache[lastpos] = plan;
if (++lastpos>=nmax) lastpos=0;
auto p = find_in_cache();
if (p) return p;
size_t lru = 0;
for (size_t i=1; i<nmax; ++i)
if (last_access[i] < last_access[lru])
lru = i;
cache[lru] = plan;
last_access[lru] = access_counter++;
}
return plan;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment