Increasing speed of python code

前端 未结 8 1843
野性不改
野性不改 2021-02-05 12:37

I have some python code that has many classes. I used cProfile to find that the total time to run the program is 68 seconds. I found that the following function in

8条回答
  •  野的像风
    2021-02-05 13:05

    It's surprising that the function shown is such a bottleneck because it's so relatively simple. For that reason, I'd double check my profiling procedure and results. However, if they're correct, the most time consuming part of your function has to be the for loop it contains, of course, so it makes sense to focus on speeding that up. One way to do this is by replacing the if/else with straight-line code. You can also reduce the attribute lookup for the append list method slightly. Here's how both of those things could be accomplished:

    def qtyDemanded(self, timePd, priceVector):
        '''Returns quantity demanded in period timePd. In addition,
        also updates the list of customers and non-customers.
    
        Inputs: timePd and priceVector
        Output: count of people for whom priceVector[-1] < utility
        '''
    
        price = priceVector[-1] # last price
        kinds = [[], []] # initialize sublists of noncustomers and customers
        kindsAppend = [kinds[b].append for b in (False, True)] # append methods
    
        for person in self.people:
            person.customer = person.utility >= price  # customer test
            kindsAppend[person.customer](person)  # add to proper list
    
        self.nonCustomers = kinds[False]
        self.customers = kinds[True]
    
        return len(self.customers)
    

    That said, I must add that it seems a little redundant to have both a customer flag in each person object and also put each of them into a separate list depending on that attribute. Not creating these two lists would of course speed the loop up further.

提交回复
热议问题