Skip to content

Instantly share code, notes, and snippets.

@pfreixes
Created January 26, 2018 20:35
Show Gist options
  • Save pfreixes/d60d00761093c3bdaf29da025a004582 to your computer and use it in GitHub Desktop.
Save pfreixes/d60d00761093c3bdaf29da025a004582 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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