我正在嘗試使用Python配置文件來加速我的代碼。我已經能夠確定幾乎所有時間都花在哪個特定功能上,但我無法弄清楚該功能在哪個時間花費的時間。瞭解Python配置文件輸出
下面我有配置文件輸出,它顯示「appendBallot」是主要的罪魁禍首,並消耗近116秒。在下面,我有「appendBallot」的代碼。
我無法從配置文件輸出中找出哪部分「appendBallot」需要優化,因爲下一個最高時間條目少於一秒。我相信你們中的很多人都可以通過我的代碼告訴我,但我想了解如何從配置文件輸出中獲取這些信息。任何幫助將不勝感激。
檔案輸出:
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 116.168 116.168 <string>:1(<module>)
1 0.001 0.001 116.168 116.168 {execfile}
1 0.003 0.003 116.167 116.167 foo.py:1(<module>)
1 0.000 0.000 116.139 116.139 ballots.py:330(loadKnown)
1 0.000 0.000 116.109 116.109 plugins.py:148(load)
1 0.196 0.196 116.108 116.108 BltBallotLoader.py:37(loadFile)
100000 114.937 0.001 115.912 0.001 ballots.py:133(appendBallot)
100000 0.480 0.000 0.790 0.000 ballots.py:117(newBallot)
316668 0.227 0.000 0.310 0.000 ballots.py:107(getNumCandidates)
417310/417273 0.111 0.000 0.111 0.000 {len}
200510 0.071 0.000 0.071 0.000 {method 'append' of 'list' objects}
99996 0.045 0.000 0.045 0.000 {method 'add' of 'set' objects}
100000 0.042 0.000 0.042 0.000 {method 'has_key' of 'dict' objects}
1 0.000 0.000 0.030 0.030 plugins.py:202(getLoaderPluginClasses)
1 0.000 0.000 0.030 0.030 plugins.py:179(getPluginClasses)
1 0.000 0.000 0.030 0.030 plugins.py:205(getLoaderPluginClass)
3 0.016 0.005 0.029 0.010 {__import__}
1 0.022 0.022 0.025 0.025 ballots.py:1(<module>)
1 0.010 0.010 0.013 0.013 BltBallotLoader.py:1(<module>)
7 0.000 0.000 0.003 0.000 re.py:227(_compile)
代碼:
def appendBallot(self, ballot, ballotID=None):
"Append a ballot to this Ballots object."
# String representation of ballot for determining whether ballot is unique
ballotString = str(list(ballot))
# Ballot as the appropriate array to conserve memory
ballot = self.newBallot(ballot)
# Assign a ballot ID if one has not been given
if ballotID is None:
ballotID = len(self.ballotIDs)
assert(ballotID not in self.ballotIDs)
self.ballotIDs.append(ballotID)
# Check to see if we have seen this ballot before
if self.uniqueBallotsLookup.has_key(ballotString):
i = self.uniqueBallotsLookup[ballotString]
self.uniqueBallotIDs[i].add(ballotID)
else:
i = len(self.uniqueBallots)
self.uniqueBallotsLookup[ballotString] = i
self.uniqueBallots.append(ballot)
self.uniqueBallotIDs.append(set([ballotID]))
self.ballotOrder.append(i)
這確實是斷言(),一直在持續。我不知道Python分析器是否會忽略assert()語句,因爲如果代碼與-O一起運行,它們將不會被執行, – 2009-09-24 23:22:02
感謝所有有用的答案。 – 2009-09-25 01:45:42
Python分析器不忽略'assert'/statements /,而不是忽略方法中的所有其他/ statements /。編寫'assert(表達式)'而不是'assert expression'不會使它變成一個可以不受限制的函數調用。 – 2009-09-25 04:36:42