一、self.*與getattr的速度對比(Python中的AI對比實驗)
完整代碼如下:
# -*- coding: UTF-8 -*-
# Author: Perry
# @Create Time: 2020-04-06 12:56
import timeit
import numpy as np
class A(object):
def __init__(self):
self.one = 1
def use(self):
tmp = self.one
class B(object):
def __init__(self):
self.one = 1
def use(self):
tmp = getattr(self, "one")
if __name__ == '__main__':
A_exp = A()
B_exp = B()
repeat = 10
number = 100000
A_time = timeit.repeat("A_exp.use()", "from __main__ import A_exp", repeat=repeat, number=number)
A_time = np.mean(A_time)
print("A time is: ", A_time)
B_time = timeit.repeat("B_exp.use()", "from __main__ import B_exp", repeat=repeat, number=number)
B_time = np.mean(B_time)
print("B time is: ", B_time)
輸出結果:
A time is: 0.011411738799999998
B time is: 0.015067042500000022
結論:可以看到使用self > getattr,但是沒有超過太多。