如何通过从对象池中自动获取和释放来减少构造函数开销?

2024-04-25 20:09:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中创建了一个不可变的数据类型,其中每秒都会创建和发布数百万个对象。在彻底分析代码之后,构造函数似乎是花费大部分时间的地方

我想到的解决方案是使用对象池,以便引用计数和内存分配一次完成。我研究过像this这样的解决方案,其中acquirerelease方法需要显式调用

但是,我实现的类类似于Python中的^{}类,其中对象由numpy自动创建和释放。例如,使用我的类的一小段代码如下所示(我使用Decimal而不是我自己的类):

import numpy as np
from decimal import Decimal

x = np.array([[Decimal(1), Decimal(2)], [Decimal(3), Decimal(4)]]
y = np.array([[Decimal(5), Decimal(6)], [Decimal(7), Decimal(8)]]

z = (x * y) + (2 * x) - (y ** 2) + (x ** 3)

因为类是不可变的,所以numpy需要为每个操作创建一个新对象,这会减慢整个代码的速度。另外,因为numpy是创建这些对象的代码,我认为我不能显式地调用acquirerelease等方法

有没有一个更好的对象池实现,或者其他一些方法,在这些方法中,一次创建大量对象,然后,释放的对象自动放回池中?换句话说,有没有另一种解决方案可以避免频繁创建和销毁对象

另外,我知道这不是使用numpy的好方法。这是我设计的第一步,希望numpy在接下来的步骤中能更有效地使用


Tags: 对象方法代码importnumpyrelease地方np
1条回答
网友
1楼 · 发布于 2024-04-25 20:09:06

你喜欢这个工作吗

class Pool():
  def __init__(self, type_, extra_alloc=1):
    self._objects = []
    self.type = type_
    self.extra_alloc = extra_alloc

  def allocate(self, size):
    self._objects.extend(object.__new__(self.type) for _ in range(size))

  def get_obj(self):
    print("Getting object")
    if not self._objects:
      self.allocate(self.extra_alloc)

    return self._objects.pop()

  def give_obj(self, obj):
    print("Object released")
    self._objects.append(obj)

class Thing(): # This can also be used as a base class
  pool = None

  def __new__(self, *args):
    return self.pool.get_obj()

  def __del__(self):
    self.pool.give_obj(self)

thing_pool = Pool(Thing)
Thing.pool = thing_pool

Thing()
# Getting object
# Object released

x = Thing()
# Getting object

del x
# Object released

相关问题 更多 >