Python有momoryerror,这是系统RAM util的限制,您已经用resource包手动定义了它。
用slots定义类使python解释器知道类的属性/成员是固定的。而且可以大大节省内存!
您可以使用__slot__减少python解释器创建dict。这将告诉解释器不要在内部创建dict并重用相同的变量。
如果python进程消耗的内存将随着时间继续增长。这似乎是:Python中的C内存分配器是如何工作的。这实际上是内存碎片,因为除非整个内存块未使用,否则分配无法调用“free”。但是内存块的使用通常与您正在创建和使用的对象不完全一致。
使用多个小字符串比较数据。一个称为interning的过程在内部使用,但是创建多个小字符串会给解释器带来负载。
最好的方法是创建工作线程或单线程池来完成您的工作,并使Worker/kill无效以释放在工作线程中附加/使用的资源。
下面的代码创建单线程工作线程:__slot__ = ('dna1','dna2','lock','errorResultMap')
lock = threading.Lock()
errorResultMap = []
def process_dna_compare(dna1, dna2):
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
futures = {executor.submit(getDnaDict, lock, dna_key): dna_key for dna_key in dna1}
'''max_workers=1 will create single threadpool'''
dna_differences_map={}
count = 0
dna_processed = False;
for future in concurrent.futures.as_completed(futures):
result_dict = future.result()
if result_dict :
count += 1
'''Do your processing XYZ here'''
logger.info('Total dna keys processed ' + str(count))
def getDnaDict(lock,dna_key):
'''process dna_key here and return item'''
try:
dataItem = item[0]
return dataItem
except:
lock.acquire()
errorResultMap.append({'dna_key_1': '', 'dna_key_2': dna_key_2, 'dna_key_3': dna_key_3,
'dna_key_4': 'No data for dna found'})
lock.release()
logger.error('Error in processing dna :'+ dna_key)
pass
if __name__ == "__main__":
dna1 = '''get data for dna1'''
dna2 = '''get data for dna2'''
process_dna_compare(dna1,dna2)
if errorResultMap != []:
''' print or write to file the errorResultMap'''
下面的代码将帮助您了解内存使用情况:
导入对象图
随机导入
进口检验class Dna(object):
def __init__(self):
self.val = None
def __str__(self):
return "dna – val: {0}".format(self.val)
def f():
l = []
for i in range(3):
dna = Dna()
#print “id of dna: {0}”.format(id(dna))
#print “dna is: {0}”.format(dna)
l.append(dna)
return l
def main():
d = {}
l = f()
d['k'] = l
print("list l has {0} objects of type Dna()".format(len(l)))
objgraph.show_most_common_types()
objgraph.show_backrefs(random.choice(objgraph.by_type('Dna')),
filename="dna_refs.png")
objgraph.show_refs(d, filename='myDna-image.png')
if __name__ == "__main__":
main()
内存使用输出:list l has 3 objects of type Dna()
function 2021
wrapper_descriptor 1072
dict 998
method_descriptor 778
builtin_function_or_method 759
tuple 667
weakref 577
getset_descriptor 396
member_descriptor 296
type 180