python 会增加内存吗,在Python中增加内存限制?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值