#!/usr/bin/env python # -*- coding: iso-8859-1 -*- # Dinko Korunic 'kreator', 2006. # exception-speed.py # script for testing exception speed for dictionary update vs. checking # the key space import random import time import timeit def first_method(): test_dict = {} for i in elem_arry: if i in test_dict: test_dict[i].append(garbage) else: test_dict[i] = [] test_dict[i].append(garbage) def second_method(): test_dict = {} for i in elem_arry: try: test_dict[i].append(garbage) except KeyError: test_dict[i] = [] test_dict[i].append(garbage) def third_method(): test_dict = {} for i in elem_arry: test_dict.setdefault(i, []).append(garbage) if __name__ == '__main__': # set the initial values random.seed(time.time()) no_elem = 262140 elem_arry = [] repeat = 30 garbage = (0, 1) # random case scenario # which elements in test_dict are going to be changed for i in xrange(0, no_elem): rand_int = random.randint(0, no_elem) elem_arry.append(rand_int) # worst case scenario # which elements in test_dict are going to be changed #for i in xrange(0, no_elem): # elem_arry.append(i) # best case scenario 1 # which elements in test_dict are going to be changed #for i in xrange(0, no_elem): # elem_arry.append(0) # best case scenario 2 # which elements in test_dict are going to be changed #for i in xrange(0, no_elem): # elem_arry.append(no_elem) t1 = timeit.Timer('first_method()', \ 'from __main__ import first_method') t2 = timeit.Timer('second_method()', \ 'from __main__ import second_method') t3 = timeit.Timer('third_method()', \ 'from __main__ import third_method') print 'with key search:', t1.timeit(repeat) print 'with exceptions:', t2.timeit(repeat) print 'with setdefault:', t3.timeit(repeat)