Created
December 22, 2011 02:56
-
-
Save rsdy/1508717 to your computer and use it in GitHub Desktop.
perftesting different ways to override an arbitrary member method in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Example output: | |
# | |
# > testing mapped version | |
# 0.015753 usec/pass | |
# > waiting 1.0s | |
# > testing rebound version | |
# 0.025296 usec/pass | |
# | |
import gc | |
import os | |
import time | |
import timeit | |
class Mapped(object): | |
def __init__(self): | |
self.function_map = {} | |
def __getattribute__(self, name): | |
fun = object.__getattribute__(self, 'function_map').get(name) | |
def wrapper(*args): | |
return fun(self, *args) | |
if fun: | |
return wrapper | |
else: | |
return object.__getattribute__(self, name) | |
def bind(self, name, function): | |
self.function_map[name] = function | |
def whoami(self): | |
return 'old function' | |
class Rebound(object): | |
def __init__(self): | |
pass | |
def whoami(self): | |
return 'old function' | |
def test(obj, what): | |
global object_to_test | |
object_to_test = obj | |
t = timeit.Timer('get_function', 'from __main__ import get_function') | |
print "> testing %s\n%f usec/pass" % (what, 1000000 * t.timeit(number=1000000)/1000000) | |
object_to_test = None | |
def get_function(): | |
return getattr(object_to_test, FUNCTION_TO_TEST) | |
def new_whoami(self): | |
return 'new function' | |
FUNCTION_TO_TEST = 'whoami' | |
if __name__ == '__main__': | |
if os.fork() == 0: | |
mapped = Mapped() | |
mapped.bind(FUNCTION_TO_TEST, new_whoami) | |
test(mapped, 'mapped') | |
else: | |
time.sleep(1) # remove this and enjoy the show | |
rebound = Rebound() | |
setattr(Rebound, FUNCTION_TO_TEST, new_whoami) | |
test(rebound, 'rebound') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment