[Linux] python腳本模擬佔用內存

應用場景:測試系統在不同內存環境下的運行情況、低於設定閾值是否觸發事件通知等。

思路:創建一個超長字符串,一個空格字符佔1字節,1024個空格佔1M,1024*1024個空格佔1G。

eatmem.py 內容如下,用法 python eatmem.py <block num>,其中block大小在腳本中設置爲200M,block num 代表將要吃掉多少個200M的內存(實際用起來會有一定誤差,可以結合free命令查看調整)。

#encoding=utf-8
import sys, time
if __name__ == '__main__':
    if(len(sys.argv) == 2):
        blocks = 0
        try:
            blocks = int(sys.argv[1])
        except ValueError:
            print("Usage: python eatmem.py <blocks to allocate,should be an integer> \n  Currently, 1 block represents 200M.")

        if(blocks > 0):
            eatFlag = True
     
            if(eatFlag):
                mem_to_eat = str(blocks * 0.2) + "GB" if (blocks > 4) else str(blocks * 200) + "MB"
                print("Will allocate about " + mem_to_eat + ". Please use 'Ctrl+C' to Release.")
                try:
                    mem_list = []
                    for i in range(0, blocks):
                        mem_list[i] = ' ' * 1024 * 1024 * 200
                    while(True):
                        time.sleep(1)
                except KeyboardInterrupt:
                    print "Will release the memory."
        else:
            print("Usage: python eatmem.py <blocks to eat,should be an integer> \n  The specified blocks should not be lower than 1.")
    else:
        print("Usage: python eatmem.py <blocks to eat,should be an integer> \n  eg: python eatmem.py 10 will allocate about 2G memory.")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章