Advertisement
Guest User

Python performance - attr vs. property

a guest
Jan 16th, 2013
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1.  
  2. '''
  3.     Property performance vs direct attribute access.
  4. '''
  5.  
  6. class A(object):
  7.    
  8.     def __init__(self, a):
  9.         self._a = a
  10.    
  11.     def __eq__(self, other):
  12.         return self.a == other.a
  13.    
  14.     @property
  15.     def a(self):
  16.         return self._a
  17.        
  18.    
  19. def test_prop(n):
  20.    
  21.     a = A(1)
  22.     for i in range(n):
  23.         a.a + 1
  24.  
  25. def test_attr(n):
  26.    
  27.     a = A(1)
  28.     for i in range(n):
  29.         a._a + 1
  30.  
  31. import cProfile
  32. n = 10**5
  33. cProfile.run('test_prop(n)')
  34. cProfile.run('test_attr(n)')
  35.  
  36. '''
  37.         100005 function calls in 0.361 seconds
  38.  
  39.   Ordered by: standard name
  40.  
  41.   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  42.        1    0.000    0.000    0.361    0.361 <string>:1(<module>)
  43.   100000    0.085    0.000    0.085    0.000 tt.py:14(a)
  44.        1    0.268    0.268    0.361    0.361 tt.py:19(test_prop)
  45.        1    0.000    0.000    0.000    0.000 tt.py:8(__init__)
  46.        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
  47.        1    0.008    0.008    0.008    0.008 {range}
  48.  
  49.  
  50.         5 function calls in 0.063 seconds
  51.  
  52.   Ordered by: standard name
  53.  
  54.   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  55.        1    0.000    0.000    0.063    0.063 <string>:1(<module>)
  56.        1    0.058    0.058    0.063    0.063 tt.py:25(test_attr)
  57.        1    0.000    0.000    0.000    0.000 tt.py:8(__init__)
  58.        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
  59.        1    0.005    0.005    0.005    0.005 {range}
  60.  
  61. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement