'How to accelerate append within a class statement
I am creating a simulation where I will be utilizing a "company" and "client" dynamic. In essence, the clients will be allocated to companies and through a shopping simulator, will migrate from company to company throughout.
Because I want to increase the size of the simulation, I am noting that certain append statements become noticably slow when I increase the number of total clients.
Here are my class statements:
class Market:
def __init__(self, clients, companies, year):
self._clients = clients
self._companies = companies
self._year = year
self._company_objs = [Company(companies, year) for _ in range(0, companies)]
self._client_objs = [Client(year, companies) for _ in range(0, clients)]
for client in self._client_objs:
company = client.get_insurer()
self._company_objs[company].insure_client(client.get_client_id())
class Company:
company_id = 0
@classmethod
def set_company_no(cls):
cls.company_id += 1
return cls.company_id-1
def __init__(self, companies, year):
self._company_id = Company.set_company_no()
self._company_year = year
self._client_list = []
def insure_client(self, client_id):
if self._client_list == []:
self._client_list.append(client_id)
else:
if client_id in self._client_list:
return
else:
self._client_list.append(client_id)
class Client:
client_id = 0
@classmethod
def set_client_no(cls):
cls.client_id += 1
return cls.client_id-1
def __init__(self, year, companies):
self._client_id = Client.set_client_no()
self._year = year
self._insurer = self.assign_company(companies)
def assign_company(self, companies):
company = np.random.randint(0, companies)
return company
In terms of potential opportunities, I am thinking that use of an numpy array of predefined size would likely speed this up (and using indexing). I say predefined since I know that numpy appends can be even slower since it is re-written each time.
This is my first time using a Class / OOP pattern. I could do this more easily with control flow code, but looking for ideas regarding how a Class construct could be composed more elegantly to perform with speed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
