Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing how slow or fast is fetch attributes and call external functions
from timeit import timeit
class Object:
def __init__(self, x):
self.x = x
class Rule:
def __init__(self, valid_values, valid_values2):
self.valid_values = valid_values
self.valid_values2 = valid_values2
rules = [Rule([x], [x]) for x in range(1000)]
objects = [Object(x) for x in range(1000)]
def cache():
cnt = 0
for rule in rules:
valid_values = rule.valid_values
valid_values2 = rule.valid_values2
for object in objects:
if not object.x in valid_values:
continue
if not object.x in valid_values2:
continue
cnt += object.x
def fetch():
cnt = 0
for rule in rules:
for object in objects:
if not object.x in rule.valid_values:
continue
if not object.x in rule.valid_values2:
continue
cnt += object.x
def fetch_and_call():
cnt = 0
for rule in rules:
for object in objects:
if filter(object, rule):
cnt += object.x
def filter(object, rule):
if not object.x in rule.valid_values:
return False
if not object.x in rule.valid_values2:
return False
return True
def run_test():
print("Cache local attributes {}".format(timeit("cache()", 'from __main__ import cache', number=10)))
print("None cache local attributes {}".format(timeit("fetch()", 'from __main__ import fetch', number=10)))
print("Call an external function {} ".format(timeit("fetch_and_call()", 'from __main__ import fetch_and_call', number=10)))
run_test()
@pfreixes

This comment has been minimized.

Copy link
Owner Author

commented Jan 26, 2018

Interpreter Cached None Cached Call external function
Python2.7-10 0.649 1.005 2.076
Python3.5 0.677 1.138 2.169
Python3.6 0.713 1.161 2.285
pypy 0.094 0.102 0.103
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.