gpt4 book ai didi

python - 如何加速数百万对象的python实例初始化?

转载 作者:太空狗 更新时间:2023-10-30 01:49:55 26 4
gpt4 key购买 nike

我定义了一个名为 Edge 的 python class,如下所示:

class Edge:
def __init__(self):
self.node1 = 0
self.node2 = 0
self.weight = 0

现在我必须使用以下方法创建大约 10^6 到 10^7 个 Edge 实例:

edges= []
for (i,j,w) in ijw:
edge = Edge()
edge.node1 = i
edge.node2 = j
edge.weight = w
edges.append(edge)

我在桌面上花了大约 2 秒的时间。有没有更快的方法呢?

最佳答案

你不能让它变得快,但我肯定会使用 __slots__以节省内存分配。还可以在创建实例时传入属性值:

class Edge:
__slots__ = ('node1', 'node2', 'weight')
def __init__(self, node1=0, node2=0, weight=0):
self.node1 = node1
self.node2 = node2
self.weight = weight

通过更新的 __init__,您可以使用列表理解:

edges = [Edge(*args) for args in ijw]

这些一起可以节省大量创建对象的时间,大约需要一半的时间。

比较创建 100 万个对象;设置:

>>> from random import randrange
>>> ijw = [(randrange(100), randrange(100), randrange(1000)) for _ in range(10 ** 6)]
>>> class OrigEdge:
... def __init__(self):
... self.node1 = 0
... self.node2 = 0
... self.weight = 0
...
>>> origloop = '''\
... edges= []
... for (i,j,w) in ijw:
... edge = Edge()
... edge.node1 = i
... edge.node2 = j
... edge.weight = w
... edges.append(edge)
... '''
>>> class SlotsEdge:
... __slots__ = ('node1', 'node2', 'weight')
... def __init__(self, node1=0, node2=0, weight=0):
... self.node1 = node1
... self.node2 = node2
... self.weight = weight
...
>>> listcomploop = '''[Edge(*args) for args in ijw]'''

和时间:

>>> from timeit import Timer
>>> count, total = Timer(origloop, 'from __main__ import OrigEdge as Edge, ijw').autorange()
>>> (total / count) * 1000 # milliseconds
722.1121070033405
>>> count, total = Timer(listcomploop, 'from __main__ import SlotsEdge as Edge, ijw').autorange()
>>> (total / count) * 1000 # milliseconds
386.6706900007557

快了将近 2 倍。

将随机输入列表增加到 10^7 项,并且时间差异保持:

>>> ijw = [(randrange(100), randrange(100), randrange(1000)) for _ in range(10 ** 7)]
>>> count, total = Timer(origloop, 'from __main__ import OrigEdge as Edge, ijw').autorange()
>>> (total / count)
7.183759553998243
>>> count, total = Timer(listcomploop, 'from __main__ import SlotsEdge as Edge, ijw').autorange()
>>> (total / count)
3.8709938440006226

关于python - 如何加速数百万对象的python实例初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53388451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com