1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
  | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import time, json
def test(data, k, count):
    times = []
    start = time.time()
    for i in range(count):
        #method 1
        try:
            v = data[k]
        except KeyError:
            v = 12
    end = time.time()
    print "method 1 spend time: %f s." % (end - start)
    times.append(end - start)
    start = time.time()
    for i in range(count):
        #method 2
        if data.has_key(k):
            v = data[k]
        else:
            v = 12
    end = time.time()
    print "method 2 spend time: %f s." % (end - start)
    times.append(end - start)
    start = time.time()
    for i in range(count):
        #method 3
        if k in data:
            v = data[k]
        else:
            v = 12
    end = time.time()
    print "method 3 spend time: %f s." % (end - start)
    times.append(end - start)
    start = time.time()
    for i in range(count):
        #method 4
        v = data.get(k)
        if v == None:
            v = 12
    end = time.time()
    print "method 4 spend time: %f s." % (end - start)
    times.append(end - start)
    return times
def main():
    print "test hit"
    data = {'a': 12}
    k = 'a'
    times1 = test(data, k, 1000000)
    print
    print "test not hit"
    data = {'a': 12}
    k = 'ab'
    times2 = test(data, k, 1000000)
    print
    print "test data IO"
    data = {'a': 12}
    k = 'a'
    fd = FileDict(data)
    times3 = test(fd, k, 5000)
    print
    import numpy as np
    import matplotlib.pyplot as plt
    ind = np.arange(4)
    p1 = plt.bar(ind, times1, width=0.2, color='r')
    p2 = plt.bar(ind+0.2, times2, width=0.2, color='g')
    p3 = plt.bar(ind+0.4, times3, width=0.2, color='b')
    plt.xticks(ind, ('method 1', 'method 2', 'method 3', 'method 4') )
    plt.legend( (p1[0], p2[0], p3[0]), ('hit', 'not hit', 'IO') )
    plt.show()
class FileDict:
    def __init__(self, data):
        open('temp.txt','w').write(json.dumps(data))
    def get(self, key):
        return json.load(open('temp.txt'))[key]
    __getitem__ = get
    def has_key(self, key):
        return json.load(open('temp.txt')).has_key(key)
    __contains__ = has_key
if __name__=="__main__":
    main()
  |