Understanding Python profile output

后端 未结 6 544
长情又很酷
长情又很酷 2021-01-02 17:39

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

6条回答
  •  一生所求
    2021-01-02 17:58

    I've had a look at your code, and it looks like you make a lot of function calls and attribute lookups as part of your 'checking' or looking ahead before leaping. You also have a lot of code dedicated to track the same condition, i.e many bits of code looking at creating 'unique' IDs.

    instead of trying to assign some kind of unique string to each ballot, couldn't you just use the ballotID (an integer number?)

    now you could have a dictionary (uniqueBallotIDs) mapping ballotID and the actual ballot object.

    the process might be something like this:

    def appendBallot(self, ballot, ballotID=None):
       if ballotID is None:
           ballotID = self._getuniqueid() # maybe just has a counter? up to you.
       # check to see if we have seen this ballot before.
       if not self._isunique(ballotID):
           # code for non-unique ballot ids.
       else:
           # code for unique ballot ids.
    
       self.ballotOrder.append(i)
    

    You might be able to handle some of your worries about the dictionary missing a given key by using a defaultdict (from the collections module). collection docs

    Edit for completeness I will include a sample usage of the defaultdict:

    >>> from collections import defaultdict            
    
    >>> ballotIDmap = defaultdict(list)
    >>> ballotID, ballot = 1, object() # some nominal ballotID and object.
    >>> # I will now try to save my ballotID.
    >>> ballotIDmap[ballotID].append(ballot)
    >>> ballotIDmap.items()
    [(1, [])]
    
        

    提交回复
    热议问题