summaryrefslogtreecommitdiff
path: root/speed-test
blob: 59620d06b844a2236da3a50847096ff8474fbe45 (plain)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/python
# Copyright 2010, 2011  Lars Wirzenius
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Excercise my B-tree implementation, for simple benchmarking purposes.
# The benchmark gets a location and nb of keys to use as command line
# arguments --location=LOCATION and --keys=KEYS.

# To debug, one can create a tracing logfile by adding arguments like:
# --trace=refcount --log=refcount.logfile
#
# If the location is the empty string, an in-memory node store is used.
# Otherwise it must be a non-existent directory name.
#
# The benchmark will do the given number of insertions into the tree, and
# measure the speed of that. Then it will look up each of those, and measure
# the lookups.


import cliapp
import cProfile
import csv
import gc
import logging
import os
import random
import shutil
import subprocess
import sys
import time
import tracing

import larch


class SpeedTest(cliapp.Application):

    def add_settings(self):
        self.settings.boolean(['profile'], 'profile with cProfile?')
        self.settings.boolean(['log-memory-use'], 'log VmRSS?')
        self.settings.string(['trace'], 
                'code module in which to do trace logging')
        self.settings.integer(['keys'], 
                'how many keys to test with (default is %default)',
                default=1000)
        self.settings.string(['location'], 
                'where to store B-tree on disk (in-memory test if not set)')
        self.settings.string(['csv'],
                'append a CSV row to FILE',
                metavar='FILE')

    def process_args(self, args):
        if self.settings['trace']:
            tracing.trace_add_pattern(self.settings['trace'])
    
        key_size = 19
        value_size = 128
        node_size = 64*1024

        n = self.settings['keys']
        location = self.settings['location']
        
        if n is None:
            raise Exception('You must set number of keys with --keys')
        
        if not location:
            forest = larch.open_forest(
                allow_writes=True, key_size=key_size, node_size=node_size,
                node_store=larch.NodeStoreMemory)
        else:
            if os.path.exists(location):
                raise Exception('%s exists already' % location)
            os.mkdir(location)
            forest = larch.open_forest(
                allow_writes=True, key_size=key_size, node_size=node_size,
                dirname=location)

        tree = forest.new_tree()
        
        # Create list of keys.
        keys = ['%0*d' % (key_size, i) for i in xrange(n)]
        ranges = []
        range_len = 10
        for i in range(0, len(keys) - range_len):
            ranges.append((keys[i], keys[i+range_len-1]))
        
        # Helper functions.
        nop = lambda *args: None
        
        # Calibrate.
        looptime = self.measure(keys, nop, nop, 'calibrate')

        # Measure inserts.
        random.shuffle(keys)
        value = 'x' * value_size
        insert = self.measure(keys, lambda key: tree.insert(key, value), 
                              forest.commit, 'insert')
            
        # Measure lookups.
        random.shuffle(keys)
        lookup = self.measure(keys, tree.lookup, nop, 'lookup')
            
        # Measure range lookups.
        random.shuffle(ranges)
        lookup_range = self.measure(ranges, 
                                    lambda x: 
                                        list(tree.lookup_range(x[0], x[1])),
                                    nop, 'lookup_range')

        # Measure count of range lookup results.
        len_lookup_range = self.measure(ranges,
                         lambda x: len(list(tree.lookup_range(x[0], x[1]))),
                         nop, 'len_lookup_range')

        # Measure count range.
        count_range = self.measure(ranges,
                                   lambda x: tree.count_range(x[0], x[1]),
                                   nop, 'count_range')

        # Measure inserts into existing tree.
        random.shuffle(keys)
        insert2 = self.measure(keys, lambda key: tree.insert(key, value),
                               forest.commit, 'insert2')

        # Measure removes from tree.
        random.shuffle(keys)
        remove = self.measure(keys, tree.remove, forest.commit, 'remove')

        # Measure remove_range. This requires building a new tree.
        keys.sort()
        for key in keys:
            tree.insert(key, value)
        random.shuffle(ranges)
        remove_range = self.measure(ranges, 
                                    lambda x: tree.remove_range(x[0], x[1]),
                                    forest.commit, 'remove_range')

        # Report
        def speed(result, i):
            if result[i] == looptime[i]:
                # computer too fast for the number of "keys" used...
                return float("infinity")
            else:
                return n / (result[i] - looptime[i])
        def report(label, result):
            cpu, wall = result
            print '%-16s: %5.3f s (%8.1f/s) CPU; %5.3f s (%8.1f/s) wall' % \
                (label, cpu, speed(result, 0), wall, speed(result, 1))

        print 'location:', location if location else 'memory'
        print 'num_operations: %d' % n
        report('insert', insert)
        report('lookup', lookup)
        report('lookup_range', lookup_range)
        report('len_lookup_range', len_lookup_range)
        report('count_range', count_range)
        report('insert2', insert2)
        report('remove', remove)
        report('remove_range', remove_range)
        if self.settings['profile']:
            print 'View *.prof with ./viewprof for profiling results.'
            
        if self.settings['csv']:
            self.append_csv(n, 
                            speed(insert, 0), 
                            speed(insert2, 0), 
                            speed(lookup, 0),
                            speed(lookup_range, 0), 
                            speed(remove, 0), 
                            speed(remove_range, 0))

        # Clean up
        if location:
            shutil.rmtree(location)

    def measure(self, items, func, finalize, profname):

        def log_memory_use(stage):
            if self.settings['log-memory-use']:
                logging.info('%s memory use: %s' % (profname, stage))
                logging.info('  VmRSS: %s KiB' %  self.vmrss())
                logging.info('  # objects: %d' % len(gc.get_objects()))
                logging.info('  # garbage: %d' % len(gc.garbage))

        def helper():
            log_memory_use('at start')
            for item in items:
                func(item)
            log_memory_use('after calls')
            finalize()
            log_memory_use('after finalize')

        print 'measuring', profname
        start_time = time.time()
        start = time.clock()
        if self.settings['profile']:
            globaldict = globals().copy()
            localdict = locals().copy()
            cProfile.runctx('helper()', globaldict, localdict, 
                            '%s.prof' % profname)
        else:
            helper()
        end = time.clock()
        end_time = time.time()
        return end - start, end_time - start_time

    def vmrss(self):
        f = open('/proc/self/status')
        rss = 0
        for line in f:
            if line.startswith('VmRSS'):
                rss = line.split()[1]
        f.close()
        return rss

    def append_csv(self, keys, insert, insert2, lookup, lookup_range,
                    remove, remove_range):
        write_title = not os.path.exists(self.settings['csv'])
        f = open(self.settings['csv'], 'a')
        self.writer = csv.writer(f, lineterminator='\n')
        if write_title:
            self.writer.writerow(('revno',
                                  'keys',
                                  'insert (random)',
                                  'insert (seq)',
                                  'lookup',
                                  'lookup_range',
                                  'remove',
                                  'remove_range'))

        if os.path.exists('.bzr'):
            p = subprocess.Popen(['bzr', 'revno'], stdout=subprocess.PIPE)
            out, err = p.communicate()
            if p.returncode != 0:
                raise cliapp.AppException('bzr failed')
            revno = out.strip()
        else:
            revno = '?'

        self.writer.writerow((revno,
                              keys,
                              self.format(insert),
                              self.format(insert2),
                              self.format(lookup),
                              self.format(lookup_range),
                              self.format(remove),
                              self.format(remove_range)))
        f.close()

    def format(self, value):
        return '%.0f' % value


if __name__ == '__main__':
    SpeedTest().run()