我對python相當陌生(我通常使用C++)。我寫了一個python腳本來使用光線跟蹤算法將Blender對象轉換爲二進制掩碼文件。蟒蛇腳本中的內存泄漏攪拌器
我結束了一個巨大的內存泄漏。對於M = 512(如下所示),該腳本在腳本運行時增加了內存使用量,最終結果是使用了高達5.7GB的內存。在腳本運行之後,這個RAM的使用也會保留,直到我關閉Blender。
我不確定open()
命令是否將打開的文件存儲在RAM中(我猜測它確實存在),但這隻會佔用256MB的RAM使用量,因爲這是產生的文件大小,也不會解釋爲什麼在fo.close()
之後RAM的使用仍然存在。
我確定有一些非常簡單的東西我很想念,但是對python不是很熟悉,我很難弄清楚它是什麼。我試着清除在pointInsideMesh()
功能使用的所有變量通過將線
axis = None
mat1 = None
mat = None
orig = None
count = None
location = None
normal = None
index = None
outside1 = None
outside2 = None
立即return
語句之前,但這並沒有插入的內存泄漏。這裏是我的代碼:
import mathutils, numpy, bpy
def pointInsideMesh(point,ob):
axes = [ mathutils.Vector((1,0,0)) ]
outside1 = False
for axis in axes:
mat1 = mathutils.Matrix(ob.matrix_world)
mat=mat1.invert()
orig = mat1*point
count = 0
while True:
location,normal,index = ob.ray_cast(orig,axis*10000.0)
if index == -1: break
count+= 1
orig = location + axis*0.00001
if (count%2 == 0):
outside1 = True
break
axes = [ mathutils.Vector((0,1,0)) ]
outside2 = False
for axis in axes:
mat1 = mathutils.Matrix(ob.matrix_world)
mat=mat1.invert()
orig = mat1*point
count = 0
while True:
location,normal,index = ob.ray_cast(orig,axis*10000.0)
if index == -1: break
count+= 1
orig = location + axis*0.00001
if (count%2 == 0):
outside2 = True
break
outside = outside1 or outside2
return not outside
ob = bpy.context.active_object
M = 512
fileOut = 'D:\images\\maskFile.txt'
fo = open(fileOut , "w")
for n in range(0,M):
for m in range(0,M):
for l in range(0,M):
if pointInsideMesh(mathutils.Vector(((l+1)/M-0.5,(m+1)/M-0.5,(n+1)/M-0.5)), ob):
fo.write("1")
else:
fo.write("0")
if l < M-1:
fo.write(" ")
fo.write("\n")
fo.write("\n")
fo.close()
任何幫助將是非常讚賞:)
更新:
import mathutils, numpy, bpy
def pointInsideMesh(point,ob):
return False
ob = bpy.context.active_object
M = 512
fileOut = 'D:\images\\maskFile.txt'
fo = open(fileOut , "w")
for n in range(0,M):
for m in range(0,M):
for l in range(0,M):
if pointInsideMesh(mathutils.Vector(((l+1)/M-0.5,(m+1)/M-0.5,(n+1)/M-0.5)), ob):
fo.write("1")
else:
fo.write("0")
if l < M-1:
fo.write(" ")
fo.write("\n")
fo.write("\n")
fo.close()
重現問題,但
import mathutils, numpy, bpy
def pointInsideMesh():
return False
ob = bpy.context.active_object
M = 512
fileOut = 'D:\images\\maskFile.txt'
fo = open(fileOut , "w")
for n in range(0,M):
for m in range(0,M):
for l in range(0,M):
if pointInsideMesh():
fo.write("1")
else:
fo.write("0")
if l < M-1:
fo.write(" ")
fo.write("\n")
fo.write("\n")
fo.close()
沒有,唯一的區別是在這兩個的第一個例子中,被測試點(和對象)的位置是被傳遞給函數,而在第二個例子中,沒有參數被傳遞。在C++中,即使按值傳遞,函數中創建的參數副本也會在函數返回時從內存中清除。但是這些參數在python中的傳遞方式不同,這一定是問題的根源,因爲我不太明白這是如何工作的。
感謝您的評論。我首先嚐試了這一點,但沒有奏效,但我已經做出了更重大的改變,試圖找出發生這種泄漏的位置。這可以在我原來的問題更新中看到。再次感謝 :) – BZ1