Understanding Python profile output

后端 未结 6 545
长情又很酷
长情又很酷 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:57

    I'll support Fragsworth by saying that you'll want to split up your function into smaller ones.

    Having said that, you are reading the output correctly: the tottime is the one to watch.

    Now for where your slowdown is likely to be:

    Since there seem to be 100000 calls to appendBallot, and there aren't any obvious loops, I'd suggest it is in your assert. Because you are executing:

    assert(ballotID not in self.ballotIDs)
    

    This will actually act as a loop. Thus, the first time you call this function, it will iterate through a (probably empty) array, and then assert if the value was found. The 100000th time it will iterate through the entire array.

    And there is actually a possible bug here: if a ballot is deleted, then the next ballot added would have the same id as the last added one (unless that were the one deleted). I think you would be better off using a simple counter. That way you can just increment it each time you add a ballot. Alternatively, you could use a UUID to get unique ids.

    Alternatively, if you are looking at some level of persistence, use an ORM, and get it to do the ID generation, and unique checking for you.

提交回复
热议问题