Python中关于类和赋值的执行时间
我尝试了改变变量值的不同方法,发现了一些我没有预料到的东西。我原以为更改值本身,而不是将新类分配给变量会更快。有人能解释为什么A比B快吗Python中关于类和赋值的执行时间,python,class,execution-time,Python,Class,Execution Time,我尝试了改变变量值的不同方法,发现了一些我没有预料到的东西。我原以为更改值本身,而不是将新类分配给变量会更快。有人能解释为什么A比B快吗 from time import time class A: def __init__(self): self.a = 0 def __add__(self, other): return self.a + other def __str__(self): return str(se
from time import time
class A:
def __init__(self):
self.a = 0
def __add__(self, other):
return self.a + other
def __str__(self):
return str(self.a)
class B:
def __init__(self):
self.b = 0
def __add__(self, other):
self.b += other
def __str__(self):
return str(self.b)
a = A()
b = B()
s = time()
for _ in range(10**6):
a = a + 1
print(a, time()-s, " seconds")
s = time()
for _ in range(10**6):
b + 1
print(b, time()-s, " seconds")
输出:
1000000 0.12671232223510742 seconds
1000000 0.2434854507446289 seconds
499999500000 0.15620923042297363 seconds
499999500000 0.2812356948852539 seconds
编辑:添加代码
s = time()
for i in range(10**6):
a = a + i
print(a, time()-s, " seconds")
s = time()
for i in range(10**6):
b + i
print(b, time()-s, " seconds")
输出:
1000000 0.12671232223510742 seconds
1000000 0.2434854507446289 seconds
499999500000 0.15620923042297363 seconds
499999500000 0.2812356948852539 seconds
我不确定您的代码是否按预期运行。方法
A.。\u add\u
仅使用参数整数1调用一次。在此之后,1被分配给变量a
,从这一刻起,循环中只添加整数
如果我们更改代码以便在每次迭代中调用该方法,我们将获得几乎相同的时间
s = time()
acc = 0
for _ in range(10**6):
acc += a + 1
print(acc, time()-s, " seconds")
s = time()
for _ in range(10**6):
b + 1
print(b, time()-s, " seconds")
结果:
1000000 0.14543867111206055 seconds
1000000 0.14631319046020508 seconds
我不理解你所说的
A.\u add\u
只调用一次,然后将整数添加到循环中。我认为它的工作原理与我的预期一致,例如,将代码更改为我在原始帖子中添加的代码,可以得到我所期望的结果。编辑:是的,现在我明白了。谢谢