我正在尝试创建一个应用程序,可以“有目的地”消耗RAM,就像我们立即指定的那样。例如,我想消耗512MB内存,那么应用程序将直接消耗512MB。
我已经在网上搜索过了,他们中的大多数都在使用while循环来填充变量或数据。但我认为这种填充RAM的方式很慢,而且可能也不准确。
我正在寻找一个关于内存管理的python库。偶然发现了这些http://docs.python.org/library/mmap.html。但是不知道如何使用这些库来一次性占用RAM空间。
我曾经见过一个食用者应用程序,但不知道它们是如何编写的……
那么,有没有其他更好的建议来立即用随机数据填充RAM呢?或者我应该只使用while循环来手动填充数据,但使用多线程使其更快?
发布于 2013-03-19 17:00:59
你不能使用像这样的结构来分配所有内存
s = ' ' * BIG_NUMBER
最好附加一个列表,如下所示
a = []
while True:
print len(a)
a.append(' ' * 10**6)
下面是一个更长的代码,它提供了更多关于内存分配限制的信息:
import os
import psutil
PROCESS = psutil.Process(os.getpid())
MEGA = 10 ** 6
MEGA_STR = ' ' * MEGA
def pmem():
tot, avail, percent, used, free = psutil.virtual_memory()
tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA
proc = PROCESS.get_memory_info()[1] / MEGA
print('process = %s total = %s avail = %s used = %s free = %s percent = %s'
% (proc, tot, avail, used, free, percent))
def alloc_max_array():
i = 0
ar = []
while True:
try:
#ar.append(MEGA_STR) # no copy if reusing the same string!
ar.append(MEGA_STR + str(i))
except MemoryError:
break
i += 1
max_i = i - 1
print 'maximum array allocation:', max_i
pmem()
def alloc_max_str():
i = 0
while True:
try:
a = ' ' * (i * 10 * MEGA)
del a
except MemoryError:
break
i += 1
max_i = i - 1
_ = ' ' * (max_i * 10 * MEGA)
print 'maximum string allocation', max_i
pmem()
pmem()
alloc_max_str()
alloc_max_array()
这是我得到的输出:
process = 4 total = 3179 avail = 2051 used = 1127 free = 2051 percent = 35.5
maximum string allocation 102
process = 1025 total = 3179 avail = 1028 used = 2150 free = 1028 percent = 67.7
maximum array allocation: 2004
process = 2018 total = 3179 avail = 34 used = 3144 free = 34 percent = 98.9
发布于 2020-09-24 03:21:45
x = bytearray(1024*1024*1000)
消耗大约1 1GB的内存
发布于 2017-03-31 07:07:57
以下是适用于我的markolopa答案的一个版本:
import os
import psutil
PROCESS = psutil.Process(os.getpid())
MEGA = 10 ** 6
MEGA_STR = ' ' * MEGA
def pmem():
try:
tot, avail, percent, used, free, active, inactive, buffers = psutil.virtual_memory()
except ValueError:
tot, avail, percent, used, free, active, inactive, buffers, cached, shared = psutil.virtual_memory()
tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA
proc = PROCESS.memory_info()[1] / MEGA
print('process = %s total = %s avail = %s used = %s free = %s percent = %s'
% (proc, tot, avail, used, free, percent))
def alloc_max_array():
i = 0
ar = []
while True:
try:
#ar.append(MEGA_STR) # no copy if reusing the same string!
ar.append(MEGA_STR + str(i))
except MemoryError:
break
i += 1
max_i = i - 1
print('maximum array allocation:', max_i)
pmem()
def alloc_max_str():
i = 0
while True:
try:
a = ' ' * (i * 10 * MEGA)
del a
except MemoryError:
break
i += 1
max_i = i - 1
_ = ' ' * (max_i * 10 * MEGA)
print('maximum string allocation', max_i)
pmem()
pmem()
alloc_max_str()
alloc_max_array()
https://stackoverflow.com/questions/6317818
复制相似问题