Clearing memory used by rpy2

大兔子大兔子 提交于 2019-11-28 10:20:55

There is a paragraph in the rpy docs hinting that you may need to run the Python garbage collector frequently when deleting or overwriting large objects:

R objects live in the R memory space, their size unbeknown to Python, and because of that it seems that Python does not always garbage collect often enough when large objects are involved. This is sometimes leading to transient increased memory usage when large objects are overwritten in loops, and although reaching a system’s memory limit appears to trigger garbage collection, one may wish to explicitly trigger the collection.

I was able to force rpy2 to free that large matrix by running gc.collect() immediately after creating the matrix, and again just after deleting it and running R's internal gc() function. Running it in a loop with a sleep -- use top to watch the memory usage increase / decrease.

Running under Python 2.6 on Ubuntu 10.0.4 with python-rpy version 2.0.8 linked to R version 2.10.1. Hope this helps you make some progress:

import gc
import time

import rpy2.robjects as R

for i in range(5):
    print 'pass %d' % i
    R.r('a = matrix(NA, 1000000, 50)')
    gc.collect()
    R.r('rm(a)')
    R.r('gc()')
    gc.collect()

    print 'sleeping..'
    time.sleep(5)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!