I\'m trying to use the Python profiler to speed up my code. I\'ve been able to identify the specific function where nearly all of the time is spent, but I can\'t figure out
You have two problems in this little slice of code:
# 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)
Firstly it appears that self.ballotIDs is a list, so the assert statement will cause quadratic behaviour. As you didn't give any documentation at all for your data structures, it's not possible to be prescriptive, but if the order of appearance doesn't matter, you could use a set instead of a list.
Secondly, the logic (in the absence of documentation on what a ballotID is all about, and what a not-None ballotID arg means) seems seriously bugged:
obj.appendBallot(ballota, 2) # self.ballotIDs -> [2]
obj.appendBallot(ballotb) # self.ballotIDs -> [2, 1]
obj.appendBallot(ballotc) # wants to add 2 but triggers assertion
Other comments:
Instead of adict.has_key(key)
, use key in adict
-- it's faster and looks better.
You may like to consider reviewing your data structures ... they appear to be slightly baroque; there may be a fair bit of CPU time involved in building them.