在我的python代码中,我尝试计算由两种不同材料组成的结构的材质响应。
检查代码后,我发现以下类型的结构使用了大量内存:
class ClassA:
# This is a class with some memory expensive properties
def __init__(self, prop_a, prop_b):
self.prop_a = prop_a
self.prop_b = prop_b
# A function
def calculateC(self, ka, kb):
C = ka * kb # some long, expensive calculation going on here
return C
class Communicator:
# This is a class will need the function handles that point to calculateC
def __init__(self, function1, function2):
self.function1 = function1
self.function2 = function2
def splitComputeCompose(self, ka, kb, ind1, ind2):
ans1 = self.function1(ka[ind1], kb[ind1]) # compute the part related to inst1
ans2 = self.function1(ka[ind2], kb[ind2]) # compute the part related to inst2
ans = [ans1, ans2] # compose the final array to return
return ans
def main():
part1 = ClassA(someValue1, someValue2)
part2 = ClassA(someValue3, someValue4)
myCommunicator = Communicator(part1.calculateC, part2.calculateC) # somehow doubles the memory usage
据我所知,问题在于传递part1.calculateC& part2.calculateC到通信器类似乎复制它们。
我该如何避免这种情况?我如何只传递函数句柄,有没有办法改进上面的结构?