Skip to content

Commit

Permalink
When the tile-join cache fills up, evict the least recently used
Browse files Browse the repository at this point in the history
  • Loading branch information
e-n-f committed Oct 4, 2023
1 parent 2af90ef commit d5a932b
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions tile-join.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <sqlite3.h>
#include <limits.h>
#include <getopt.h>
#include <sys/time.h>
#include <vector>
#include <string>
#include <map>
Expand Down Expand Up @@ -394,6 +395,20 @@ struct tilecmp {
}
} tilecmp;

double now() {
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0) {
perror("gettimeofday");
exit(EXIT_IMPOSSIBLE);
}
return (double) tv.tv_sec + tv.tv_usec / 1000000000.0;
}

struct mvt_tile_with_time {
mvt_tile tile;
double when;
};

// The `tileset_reader` is an iterator through the tiles of a tileset,
// in z/x/tms_y order.
//
Expand Down Expand Up @@ -436,8 +451,7 @@ struct tileset_reader {
bool overzoom_consumed_at_this_zoom = false;

// parent tile cache
std::map<zxy, mvt_tile> overzoom_cache;
size_t overzoom_cache_seq;
std::map<zxy, mvt_tile_with_time> overzoom_cache;

// for iterating mbtiles
sqlite3 *db = NULL;
Expand Down Expand Up @@ -761,22 +775,28 @@ struct tileset_reader {
auto f = overzoom_cache.find(parent_tile);
if (f == overzoom_cache.end()) {
if (overzoom_cache.size() > 1000) {
// evict something to make room
// evict the oldest tile to make room

auto to_erase = overzoom_cache.begin();
for (size_t i = 0; i < overzoom_cache_seq; i++) {
++to_erase;
for (auto here = overzoom_cache.begin(); here != overzoom_cache.end(); ++here) {
if (here->second.when < to_erase->second.when) {
to_erase = here;
}
}

overzoom_cache.erase(to_erase);
}

source = get_tile(parent_tile);
overzoom_cache.emplace(parent_tile, source);
static std::atomic<size_t> count(0);
count++;

mvt_tile_with_time to_cache;
to_cache.tile = source;
to_cache.when = now();

overzoom_cache.emplace(parent_tile, to_cache);
} else {
source = f->second;
f->second.when = now();
source = f->second.tile;
}

if (pthread_mutex_unlock(&retrieve_lock) != 0) {
Expand Down

0 comments on commit d5a932b

Please sign in to comment.