Ben Jeffrey
Ben Jeffrey

Reputation: 951

Amount of available memory in cache initialised with the R function: `memoise::memoise()`

I am repeatedly calling a memoised function initialised as so:

library(memoise)
memoised_func <- memoise::memoise(func)

I am aware that I can set the size of the cache allocated to memoised_func with the cache argument (https://www.rdocumentation.org/packages/memoise/versions/2.0.0/topics/memoise). But is there a way to see how much free memory there is in the cache for at any one point in time? I am asking because I want to know if it is filling up and therefore my programme could be sped up by increasing the size of the cache.

(I'm running R 4.0.2 on Ubuntu 20.10 in case that's relevant)

Upvotes: 1

Views: 97

Answers (1)

Ben Jeffrey
Ben Jeffrey

Reputation: 951

I found a workaround which solves this problem.

By default memoise uses cachem::cache_mem to create the cache. Alternatively, I can use cachem::cache_disk which allows me to specify the location of the cache on the file system. Then it's trivial to see how much free memory there is in the cache:

library(memoise)
library(cachem)

#assigned in global scope
cache.dir <<- tempdir() 
cache.size <<- 2048 * 1024^2

memoised_func <- memoise::memoise(func, 
                                cache = cachem::cache_disk(
                                                dir = cache.dir,
                                                max_size = cache.size))

cache.percent.full <- function() {
    used.mem <- file.size(dir(cache.dir, full.names = TRUE)) %>% 
                    sum() 
    return(used.mem/cache.size * 100)
}

Upvotes: 1

Related Questions