Skip to content

Instantly share code, notes, and snippets.

@lclarkmichalek
Created January 21, 2012 16:43
Show Gist options
  • Save lclarkmichalek/1653245 to your computer and use it in GitHub Desktop.
Save lclarkmichalek/1653245 to your computer and use it in GitHub Desktop.
Benchmark of lazy properties in python
from __future__ import print_function
import timeit
t1 = """
class Test():
_bar = None
@property
def bar(self):
if self._bar is not None:
return self._bar
self._bar = 42
return self._bar
test = Test()
"""
t2 = """
class Test():
@property
def bar(self):
self.bar = 42
return 42
test = Test()
"""
t3 = """
class LazyProperty(object):
def __init__(self, func):
self._func = func
self.__name__ = func.__name__
self.__doc__ = func.__doc__
def __get__(self, obj, klass=None):
if obj is None: return None
result = obj.__dict__[self.__name__] = self._func(obj)
return result
class Foo(object):
@LazyProperty
def bar(self):
return 42
test = Foo()
"""
tests = (t1, t2, t3)
print("Calculation and one lookup")
for t in tests:
timer = timeit.Timer("test.bar; test.bar", t)
try:
print("%.2f usec/pass" % (1000000 * timer.timeit(number=100000)/100000))
except:
timer.print_exc()
print("One post calculation lookup")
for t in tests:
timer = timeit.Timer("test.bar", t + "\ntest.bar")
try:
print("%.2f usec/pass" % (1000000 * timer.timeit(number=100000)/100000))
except:
timer.print_exc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment