from timeit import default_timerclass Test(object): def __init__(self): self.a = 1.0class Test1(object): def __init__(self): self.a = 1.0 def __getattribute__(self,item): return object.__getattribute__(self,item)class Test2(object): def __init__(self): self.a = 1.0 def __getattribute__(self,item): return super(Test2,self).__getattribute__(item)class ObjectWrapper(object): def __init__(self,ocls,obj=None): self.__ocls = ocls self.__obj = None if obj is None or isinstance(obj,ocls): self.__obj = obj else: raise RuntimeError(''.join(str(x) for x in ("The value is ",type(obj),\ ",but it must be None or instance of ",self.__ocls.__name__))) def set_inner_object(self,obj): if obj is None or isinstance(obj,self.__ocls): self.__obj = obj else: raise RuntimeError(''.join(str(x) for x in ("The value is ",self.__ocls.__name__))) def __getattr__(self,name): return getattr(self.__obj,name)def main(): x = test() x1 = Test1() x2 = Test2() xw = ObjectWrapper(Test,x) accsum = 0.0 accsum1 = 0.0 accsum2 = 0.0 accsumw = 0.0 s = default_timer() for i in xrange(0,100000000): accsum += x.a e = default_timer() s1 = default_timer() for i in xrange(0,100000000): accsum1 += x1.a e1 = default_timer() s2 = default_timer() for i in xrange(0,100000000): accsum2 += x2.a e2 = default_timer() sw = default_timer() for i in xrange(0,100000000): accsumw += xw.a ew = default_timer() print "speed factor Test1/Test: ",(e1 - s1) / (e - s) print "speed factor Test2/Test: ",(e2 - s2) / (e - s) print "speed factor Test wrapped/Test: ",(ew - sw) / (e - s)if __name__ == '__main__': main()
压倒一切的影响是巨大的.这是输出:
speed factor Test1/Test: 6.32820892871speed factor Test2/Test: 8.4176175507speed factor Test wrapped/Test: 11.6202852701
Python是不正常的(python不是我的母语编程语言),为什么?
这是压倒一切的价格和/和溺爱的价格?!
如何提高性能?
解决方法 是的,你使用的抽象越多,事情就越慢.主要的Python实现使用哈希表来处理所有事情,而额外的间接层通常意味着额外的哈希表查找.这里有一些反汇编供你咀嚼:
>>> dis.dis(Test2.__getattribute__) 5 0 LOAD_GLOBAL 0 (super) 3 LOAD_GLOBAL 1 (Test2) 6 LOAD_FAST 0 (self) 9 CALL_FUNCTION 2 (2 positional,0 keyword pair) 12 LOAD_ATTR 2 (__getattribute__) 15 LOAD_FAST 1 (item) 18 CALL_FUNCTION 1 (1 positional,0 keyword pair) 21 RETURN_VALUE
请注意,对于每个LOAD_GLOBAL,您基本上都在进行哈希表查找,然后还有另一个哈希表查找LOAD_ATTR(我认为).你正在做更多的工作,所以需要更多的时间.除此之外,还要增加执行您不需要的功能的成本.
总结以上是内存溢出为你收集整理的python – 优化覆盖/溺爱(覆盖__getattribute __ / __ getattr__)全部内容,希望文章能够帮你解决python – 优化覆盖/溺爱(覆盖__getattribute __ / __ getattr__)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)