Avsnitt 4. Kapitel 5
single
Challenge: Memory Optimization Audit
Svep för att visa menyn
Uppgift
Svep för att börja koda
You are auditing a data model used in a financial reporting system. Your task is to apply the memory optimization techniques from this section to reduce the footprint of the Position class and verify the improvements with sys.getsizeof().
You are given the following starting class and dataset:
class Position:
def __init__(self, position_id, ticker, quantity, price):
self.position_id = position_id
self.ticker = ticker
self.quantity = quantity
self.price = price
tickers = ["AAPL", "MSFT", "GOOG", "AMZN", "TSLA"]
- Import
sysandcopy. - Define a class
PositionOptimizedwith__slots__ = ("position_id", "ticker", "quantity", "price")and the same__init__asPosition. - Create an instance of
Positioncalledpos_originalwith values(1, "AAPL", 100, 189.50). - Create an instance of
PositionOptimizedcalledpos_optimizedwith the same values. - Store
sys.getsizeof(pos_original)insize_originalandsys.getsizeof(pos_optimized)insize_optimized. - Create a shallow copy of
pos_original.__dict__calledbudget_copyusingcopy.copy(). - Print
size_original,size_optimized, andbudget_copy.
Lösning
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 4. Kapitel 5
single
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal