import time import random from operator import itemgetter L = 10000 def benchmark_class(cls): objects = [cls() for _ in xrange(L)] dict1_items = [(o, i) for i, o in enumerate(objects)] set1_items = objects # shuffled version shuffled_dict1_items = list(dict1_items) random.shuffle(shuffled_dict1_items) shuffled_set1_items = map(itemgetter(0), shuffled_dict1_items) def time_dict_creation(): t1 = time.time() for repeat in xrange(1000): d = dict(dict1_items) t2 = time.time() return t2 - t1 def time_set_creation(): t1 = time.time() for repeat in xrange(1000): d = set(set1_items) t2 = time.time() return t2 - t1 def time_shuffled_dict_creation(): t1 = time.time() for repeat in xrange(1000): d = dict(shuffled_dict1_items) t2 = time.time() return t2 - t1 def time_shuffled_set_creation(): t1 = time.time() for repeat in xrange(1000): d = set(shuffled_set1_items) t2 = time.time() return t2 - t1 def time_dict_lookup(): a, b, c, d, e, f, g, h = shuffled_set1_items[:8] table = dict(dict1_items) t1 = time.time() for repeat in xrange(1000000): table[a] table[b] table[c] table[d] table[e] table[f] table[g] table[h] table[a] table[b] table[c] table[d] table[e] table[f] table[g] table[h] t2 = time.time() return t2 - t1 def time_set_lookup(): a, b, c, d, e, f, g, h = shuffled_set1_items[:8] table = set(set1_items) t1 = time.time() for repeat in xrange(1000000): a in table b in table c in table d in table e in table f in table g in table h in table a in table b in table c in table d in table e in table f in table g in table h in table t2 = time.time() return t2 - t1 def time_set_difference(): table = set(set1_items) other = set(table) t1 = time.time() for repeat in xrange(3000): other - table t2 = time.time() return t2 - t1 print "--- With type %r ---" % cls.__name__ print "dict creation (shuffled): ", time_shuffled_dict_creation() print "dict creation: ", time_dict_creation() print "dict lookup: ", time_dict_lookup() print "set creation (shuffled): ", time_shuffled_set_creation() print "set creation: ", time_set_creation() print "set lookup: ", time_set_lookup() print "set difference: ", time_set_difference() if __name__ == '__main__': class UserClass(object): pass benchmark_class(object) benchmark_class(UserClass)