小编Ayu*_*har的帖子

为什么使用__slots__会减慢此代码的速度?

我读过《 __slots__用法》吗?__slots__在Python 中使用实际上可以节省时间。但是,当我尝试使用花费时间时datetime,结果却相反。

import datetime as t

class A():
    def __init__(self,x,y):
        self.x = x
        self.y = y

t1 = t.datetime.now()
a = A(1,2)
t2 = t.datetime.now()
print(t2-t1)
Run Code Online (Sandbox Code Playgroud)

...给出了输出:0:00:00.000011 并使用插槽:

import datetime as t

class A():
    __slots__ = 'x','y'
    def __init__(self,x,y):
        self.x = x
        self.y = y

t1 = t.datetime.now()
a = A(1,2)
t2 = t.datetime.now()
print(t2-t1)
Run Code Online (Sandbox Code Playgroud)

...给出了输出: 0:00:00.000021

使用插槽实际上花费了更长的时间。为什么我们需要使用__slots__呢?

python performance time class slots

1
推荐指数
2
解决办法
1105
查看次数

标签 统计

class ×1

performance ×1

python ×1

slots ×1

time ×1