Commit ea716d65 authored by Martin Reinecke's avatar Martin Reinecke
Browse files

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. ...@@ -41,6 +41,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#error This file requires at least C++11 support. #error This file requires at least C++11 support.
#endif #endif
#include <array>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <cstdlib> #include <cstdlib>
...@@ -2266,23 +2267,44 @@ template<typename T0> class pocketfft_r ...@@ -2266,23 +2267,44 @@ template<typename T0> class pocketfft_r
template<typename T> shared_ptr<T> get_plan(size_t length) template<typename T> shared_ptr<T> get_plan(size_t length)
{ {
constexpr size_t nmax=10; constexpr size_t nmax=10;
static vector<shared_ptr<T>> cache(nmax); static array<shared_ptr<T>, nmax> cache;
static size_t lastpos=0; static array<size_t, nmax> last_access{{0}};
static size_t access_counter = 0;
static mutex mut; static mutex mut;
auto find_in_cache = [&]() -> shared_ptr<T>
{ {
lock_guard<mutex> lock(mut);
for (size_t i=0; i<nmax; ++i) for (size_t i=0; i<nmax; ++i)
if (cache[i] && (cache[i]->length()==length)) 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 cache[i];
} }
return nullptr;
};
{
lock_guard<mutex> lock(mut);
auto p = find_in_cache();
if (p) return p;
}
auto plan = make_shared<T>(length); auto plan = make_shared<T>(length);
{ {
lock_guard<mutex> lock(mut); lock_guard<mutex> lock(mut);
for (size_t i=0; i<nmax; ++i) auto p = find_in_cache();
if (cache[i] && (cache[i]->length()==length)) if (p) return p;
return cache[i];
cache[lastpos] = plan; size_t lru = 0;
if (++lastpos>=nmax) lastpos=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; 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