我正在幫朋友在他寫的C#XNA遊戲中發現內存泄漏。 我建議我們試着檢查每個方法被調用的次數。 爲了保持計數,我寫了一個python腳本,增加了2行來更新一個Dictionary的細節。
基本上我寫了一個python腳本來修改一些400〜2個必需的行的方法。 這段代碼可能會幫助別人做更多的事情,比如OP想要的東西。
該代碼使用第3行配置的路徑,並在處理.cs文件時遞歸迭代。它也有子目錄。
當它找到一個cs文件時,它會查找方法聲明,它會盡可能地小心。做一個備份 - 如果我的腳本違反了你的代碼,我不負責任!
import os, re
path="D:/Downloads/Dropbox/My Dropbox/EitamTool/NetworkSharedObjectModel"
files = []
def processDir(path, files):
dirList=os.listdir(path)
for fname in dirList:
newPath = os.path.normpath(path + os.sep + fname)
if os.path.isdir(newPath):
processDir(newPath, files)
else:
if not newPath in files:
files.append(newPath)
newFile = handleFile(newPath)
if newPath.endswith(".cs"):
writeFile(newPath, newFile)
def writeFile(path, newFile):
f = open(path, 'w')
f.writelines(newFile)
f.close()
def handleFile(path):
out = []
if path.endswith(".cs"):
f = open(path, 'r')
data = f.readlines()
f.close()
inMethod = False
methodName = ""
namespace = "NotFound"
lookingForMethodDeclerationEnd = False
for line in data:
out.append(line)
if lookingForMethodDeclerationEnd:
strippedLine = line.strip()
if strippedLine.find(")"):
lookingForMethodDeclerationEnd = False
if line.find("namespace") > -1:
namespace = line.split(" ")[1][0:-2]
if not inMethod:
strippedLine = line.strip()
if isMethod(strippedLine):
inMethod = True
if strippedLine.find(")") == -1:
lookingForMethodDeclerationEnd = True
previousLine = line
else:
strippedLine = line.strip()
if strippedLine == "{":
methodName = getMethodName(previousLine)
out.append(' if (!MethodAccess.MethodAccess.Counter.ContainsKey("' + namespace + '.' + methodName + '")) {MethodAccess.MethodAccess.Counter.Add("' + namespace + '.' + methodName + '", 0);}')
out.append("\n" + getCodeToInsert(namespace + "." + methodName))
inMethod = False
return out
def getMethodName(line):
line = line.strip()
lines = line.split(" ")
for littleLine in lines:
index = littleLine.find("(")
if index > -1:
return littleLine[0:index]
def getCodeToInsert(methodName):
retVal = " MethodAccess.MethodAccess.Counter[\"" + methodName + "\"]++;\n"
return retVal
def isMethod(line):
if line.find("=") > -1 or line.find(";") > -1 or line.find(" class ") > -1:
return False
if not (line.find("(") > -1):
return False
if line.find("{ }") > -1:
return False
goOn = False
if line.startswith("private "):
line = line[8:]
goOn = True
if line.startswith("public "):
line = line[7:]
goOn = True
if goOn:
return True
return False
processDir(path, files)
沒有這一要求來自哪裏? – 2009-01-06 14:01:06
我想想,把一個try/catch是不要做的事情,但真正的aswer在這裏使用正則表達式..這就是爲什麼真正的答案是不同的比,如果有什麼在你的catch塊,如發生異常的最投票 – erdogany 2009-01-13 15:40:27
在RC.GetString()?爲了以防萬一,你不應該再試一試嗎?通過閱讀問題[開玩笑] ;-) – 2010-04-12 05:46:30