Increasing speed of python code

前端 未结 8 1813
野性不改
野性不改 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:25

    You can eliminate some lookups by using local function aliases:

    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]
        self.customers = []
        self.nonCustomers = []
    
        # local function aliases
        addCust = self.customers.append
        addNonCust = self.nonCustomers.append
    
        for person in self.people:
            if person.utility >= price:             
                person.customer = 1
                addCust(person)
            else:
                person.customer = 0
                addNonCust(person)
    
        return len(self.customers)
    

提交回复
热议问题