Saturday, February 18, 2017

[ Level 1 ] Limit memory usage in Python program

We could limit memory usage in Python program.
#!/usr/bin/env python3.5
import resource

def show_memory_limit():
    soft, hard = resource.getrlimit(resource.RLIMIT_DATA)
    print 'Soft limit changed to :', soft
    print 'Hard limit changed to :', hard

def set_memory_limit(soft, hard):
    resource.setrlimit(resource.RLIMIT_DATA, (soft, hard)) #limit to one kilobyte

if __name__ == '__main__':
    show_memory_limit()
    set_memory_limit(1024, 2048)
    show_memory_limit()

Wish this helps.

regards,
Stanley Huang