Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Release memory by gc() in silence

I am running R code in ubuntu and want to release some memory. After I remove (rm()) variables, I call gc(). It seems it works. But how can make it work in silence (i.e. don't report the message). I tried to set gcinfo(verbose=FALSE), but gc() still reports the message.

gcinfo(verbose=FALSE)
# [1] FALSE
gc()
#             used  (Mb) gc trigger   (Mb)  max used   (Mb)
# Ncells    256641  13.8     467875   25.0    350000   18.7
# Vcells 103826620 792.2  287406824 2192.8 560264647 4274.5
like image 346
Quanwei Zhang Avatar asked Oct 24 '14 17:10

Quanwei Zhang


People also ask

Does GC collect release memory?

Memory releaseWhen the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots.

What does GC () do?

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically.

How do you release memory in Java?

In Java, the programmer allocates memory by creating a new object. There is no way to de-allocate that memory. Periodically the Garbage Collector sweeps through the memory allocated to the program, and determines which objects it can safely destroy, therefore releasing the memory.

How does GC collect work?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.


1 Answers

The invisible() function is useful for this. One way would be to write a little gc() wrapper function of your own that without any arguments returns gc() invisibly.

gcQuiet <- function(quiet = TRUE, ...) {
    if(quiet) invisible(gc()) else gc(...)
}

gcQuiet()        ## runs gc() invisibly

gcQuiet(FALSE)
#          used (Mb) gc trigger (Mb) max used (Mb)
# Ncells 283808 15.2     531268 28.4   407500 21.8
# Vcells 505412  3.9    1031040  7.9   896071  6.9

gcQuiet(FALSE, verbose=TRUE)
# Garbage collection 26 = 12+1+13 (level 2) ... 
# 15.2 Mbytes of cons cells used (53%)
# 3.9 Mbytes of vectors used (49%)
#          used (Mb) gc trigger (Mb) max used (Mb)
# Ncells 283813 15.2     531268 28.4   407500 21.8
# Vcells 505412  3.9    1031040  7.9   896071  6.9
like image 111
Rich Scriven Avatar answered Sep 19 '22 07:09

Rich Scriven