Source

unitbench / src / unitbench.py

  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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
'''
Copyright (c) 2011, Joseph LaFata
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the unitbench nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
from __future__ import division

from collections import deque, Iterable
from functools import partial
from operator import attrgetter, itemgetter

import inspect
import math
import os
import re
import string
import sys
import time

if sys.version_info < (3, 0):
    maxint = sys.maxint
    fname = "func_name"
else:
    xrange = range
    maxint = sys.maxsize
    fname = "__name__"

if sys.platform == "win32":
    get_time = time.clock
else:
    get_time = time.time


class TimeSet(object):
    __slots__ = ["wall", "user", "system"]

    def __init__(self, wall, user, system):
        self.wall = wall
        self.user = user
        self.system = system


class BenchResult(object):
    """
    This contains the results of running a benchmark.

    It contains the mean, variance, standard deviation, minimum,
    and maximum.  Each of these attributes are available for
    user, wall, and system time.

    Times:
     * wall
     * user
     * system

    Statistics:
     * min
     * max
     * mean
     * variance
     * std_dev (standard deviation)

    Combine one of the times and one of the statistics to get
    the appropriate attribute.
    
    The call_count is also included in the BenchResult.
    
    Examples:
     * wall_mean - Mean wall clock time
     * user_std_dev - Standard deviation of user time
     * system_variance - Variance of system (kernel) time
     * wall_min - Minimum wall clock time
     * and so on...
    """

    def __init__(self, name, value, times=None):
        self.name = name
        self.value = str(value)
        self.times = times
    
    def add_time(self, t):
        if self.times == None:
            self.times = []
        if isinstance(t, Iterable):
            time_values = filter(lambda x: isinstance(x, TimeSet), t) 
            self.times.extend(time_values)
        elif isinstance(t, TimeSet):
            self.times.append(t)
           
    def calculate_stats(self):
        
        if self.times == None:
            return self
        
        self.call_count = len(self.times) 
        
        time_types = ["wall", "user", "system"]
        for type in time_types:
            minimum = maxint
            maximum = -maxint
            count = 0
            sum = 0
            sum_2 = 0

            mean = 0.0
            variance = 0.0
            std_dev = 0.0

            if len(self.times) > 0:
                for t in self.times:
                    currentTime = getattr(t, type)
    
                    count += 1
                    sum += currentTime
                    sum_2 += currentTime ** 2
                    minimum = min(currentTime, minimum)
                    maximum = max(currentTime, maximum)

                mean = sum / count
                variance = (sum_2 / count) - (mean ** 2)
                if variance < 0.0:
                    variance = 0.0
                std_dev = math.sqrt(variance)

                setattr(self, type + "_min", minimum)
                setattr(self, type + "_max", maximum)
                setattr(self, type + "_mean", mean)
                setattr(self, type + "_variance", variance)
                setattr(self, type + "_stddev", std_dev)
        return self

class BenchBase(object):
    
    def _callable_function(self, obj, attrname):
        def wrapper():
            if hasattr(obj, attrname):
                method = getattr(obj, attrname)
                if hasattr(method, '__call__'):
                    method()
        return wrapper
    
    def _run_benchmark(self, method):
        setup = self._callable_function(method, "setup")
        teardown = self._callable_function(method, "teardown")
        # warmup the function
        for i in xrange(self.warmup()):
            setup()
            try:
                method()
            except:
                teardown()
                raise
            teardown()

        # run the benchmark
        times = []
        for i in xrange(self.repeats()):
            setup()
            try:
                times.append(self._time_call(method))
            except:
                teardown()
                raise
            teardown()
        
        return BenchResult(getattr(method, fname), method.value, times)
        
    def _time_call(self, method):
        start_user_system = os.times()
        start = get_time()

        method.ret_val = method()

        end = get_time()
        end_user_system = os.times()
        
        return TimeSet(end - start,
                       end_user_system[0] - start_user_system[0],
                       end_user_system[1] - start_user_system[1])

class FunctionProfiler(BenchBase):
    __slots__ = ["repeats", "warmup", "results", "track_parameters"]
    
    @staticmethod
    def _to_str(x):
        if isinstance(x, str):
            return "\"" + x + "\""
        if hasattr(x, "__name__"):
            return x.__name__
        return str(x)
    
    @staticmethod
    def _args_to_str(*args, **kwargs):
        to_str = FunctionProfiler._to_str
        value = ''
        if len(args) + len(kwargs) == 0:
            return 'None'
        
        if len(args) > 0:
            value = '[' + ', '.join(map(to_str, args)) + ']'
        
        if len(kwargs) > 0:
            if len(value) > 0:
                value += ' '
            sorted_kwargs = sorted(kwargs.iteritems(), key=itemgetter(0))
            value += '{' + ', '.join(
                 map(lambda x: x[0] + ':' + to_str(x[1]), sorted_kwargs)) + '}'
        return value
    
    @staticmethod
    def _wrap_int(x):
        def wrapper():
            return x
        return wrapper
    
    def __init__(self, repeats=1, warmup=0, track_parameters=False):
        self.repeats = FunctionProfiler._wrap_int(repeats)
        self.warmup = FunctionProfiler._wrap_int(warmup)
        self.track_parameters = track_parameters
        
        self.results = {}
        
    def __call__(self, func):
        def wrapper(*args, **kwargs):
            func_call = partial(func, *args, **kwargs);
            
            func_call.value = FunctionProfiler._args_to_str(args, kwargs)   
            func_call.__name__ = func.__name__
            func_call.func_name = func.func_name
            
            r = self._run_benchmark(func_call)
            
            key = r.name
            if self.track_parameters:
                key += r.value
                
            if key in self.results:
                self.results[key].add_time(r.times)
            else:
                self.results[key] = r
            
            return func_call.ret_val
        return wrapper
    
    def write_results(self, reporter=None):
        if reporter == None:
            reporter = ConsoleReporter(group_by=ConsoleReporter.GroupType.FUNCTION)
        results = sorted(self.results, key = lambda x : len(self.results[x]))
        reporter.write_results(results)

class Benchmark(BenchBase):
    """
    """

    def setup(self):
        "Hook method called once before every run of each benchmark."
        pass

    def teardown(self):
        "Hook method called once after every run of each benchmark."
        pass

    def input(self):
        """Hook method for providing the input to the benchmark.  None
        should not be passed into a benchmark function.  It is used
        as a marker that no arguments are present.

        A list containing only 0 is used as a default.
        """
        return [0]

    def repeats(self):
        """Hook method for the number of times to repeat the benchmark
        (default 7)"""
        return 7

    def warmup(self):
        """Hook method for the number of warmup runs to do (default 1)

        The warmup will run for each benchmark function with each value.
        """
        return 1

    def run(self, reporter=None):
        """This should generally not be overloaded.  Runs the benchmark
        functions that are found in the child class.
        """
        if not reporter:
            reporter = ConsoleReporter()
        benchmarks = sorted(self._find_benchmarks())

        results = []
        for value in self.input():
            for b in benchmarks:
                method = getattr(self, b)
                arg_count = len(inspect.getargspec(method)[0])

                func_call = None
                if arg_count == 2:
                    func_call = partial(method, value)
                elif arg_count == 1:
                    func_call = partial(method)
                func_call.value = value   
                func_call.__name__ = method.__name__
                func_call.func_name = method.func_name
                func_call.setup = self.setup
                func_call.teardown = self.teardown
                
                r = self._run_benchmark(func_call)
                r.name = Benchmark._function_name_to_title(r.name)
                results.append(r)
        reporter.write_results(results)
    
    @staticmethod
    def _function_name_to_title(name):
        output = name
        if output.startswith("bench"):
            output = output[5:]
        if output.find("_") != -1:
            return string.capwords(output.replace("_", " ").strip())
        else:
            s1 = re.sub('(.)([A-Z][a-z]+)', r'\1 \2', output)
            return string.capwords(
                        re.sub('([a-z0-9])([A-Z])', r'\1 \2', s1).strip())
            
    def _find_benchmarks(self):
        """Return a suite of all tests cases contained in testCaseClass"""
        def is_bench_method(attrname, prefix="bench"):
            return (attrname.startswith(prefix) and
                    hasattr(getattr(self.__class__, attrname), '__call__'))
        return list(filter(is_bench_method, dir(self.__class__)))

class Reporter(object):
    """
    This is the base class for benchmark result reporting.  If
    you'd like to write a custom importer this is the class to extend.
    """
    
    def write_results(self, results):
        """
        Override this method to output the results of the benchmark
        run.  Results is a list of BenchResult objects.  See the 
        BenchResult documentation for the information it contains.
        """
        pass

class ConsoleReporter(Reporter):
    class GroupType(object):
        FUNCTION = "name"
        VALUE = "value"
        
        @staticmethod
        def other(s):
            if s == ConsoleReporter.GroupType.FUNCTION:
                return ConsoleReporter.GroupType.VALUE
            else:
                return ConsoleReporter.GroupType.FUNCTION
    
    @staticmethod
    def count_digits(a):
        ret = 0
        while a > 0:
            a //= 10
            ret += 1
        return ret
        
    def __init__(self, output_stream=sys.stdout, group_by=GroupType.VALUE):
        self.stream = output_stream
        self.group_by = group_by
    
    def _make_key(self, title, length, key):
        if len(title) >= length:
            number = len(key)+1
            digits = ConsoleReporter.count_digits(number)
            key.append(title)            
            return title[length-6-digits:] + "...[{0}]".format(number)
        return title
        
    def write_results(self, results):
        
        results = map(lambda x: x.calculate_stats(), results)
        getter = attrgetter(self.group_by)
        other = attrgetter(ConsoleReporter.GroupType.other(self.group_by))
        results.sort(key=getter)
        
        results = deque(results)
        
        first_title = self.group_by.title() + ": "
        title_len = len(first_title)
        while len(results) > 0:
            key = []
            
            length = 40 - title_len
            title_format = first_title + "{0:<" + str(length) + "}{1:>10}{2:>10}{3:>10}\n"
            
            title_name = getter(results[0])
            display_name = self._make_key(title_name, length, key)
            
            self.stream.write(title_format.format(display_name, "user", "sys", "real"))
            self.stream.write("=" * 70 + "\n")
            
            while len(results) > 0:
                if getter(results[0]) != title_name:
                    break
                r = results.popleft()
                if (hasattr(r, "user_mean") and
                    hasattr(r, "system_mean") and hasattr(r, "wall_mean")):
                    
                    o = self._make_key(other(r), 40, key)
                    self.stream.write("{0:<40} {1:>9.4} {2:>9.4} {3:>9.4}\n"
                                      .format(o, r.user_mean,
                                              r.system_mean, r.wall_mean))
            if len(key) > 0:
                self.stream.write("Key:\n")
                for idx, k in enumerate(key, start=1):
                    self.stream.write("{0}: {1}\n".format(idx, k))
            self.stream.write("\n")

 
class CsvReporter(Reporter):
    
    def __init__(self, output_stream=sys.stdout, time_type="wall"):
        self.stream = output_stream
        self.time_type = time_type
    
    def write_results(self, results):
        
        output = []
        for r in results:
            r.calculate_stats()
            if hasattr(r, self.time_type + "_mean"):
                output.append(str(getattr(r, self.time_type + "_mean")))
        if len(output) > 0:
            self.stream.write(results[0].value + "," + ",".join(output))
            self.stream.write("\n")