Ticket #2245: deferbenchmark.patch

File deferbenchmark.patch, 2.1 KB (added by Peaker, 9 years ago)
  • doc/core/benchmarks/printtimer.py

     
     1"""A Timer that prints the results"""
     2
     3import gc
     4gc.disable()
     5print 'Disabled GC'
     6
     7def timeit(func, iter = 1000, *args, **kwargs):
     8    """timeit(func, iter = 1000 *args, **kwargs) -> elapsed time
     9   
     10    calls func iter times with args and kwargs, returns time elapsed
     11    """
     12
     13    import time
     14    r = xrange(iter)
     15    times = []
     16    clocks = []
     17    outer_iter = kwargs.pop('outer_iter', 1)
     18    for i in xrange(outer_iter):
     19        t = time.time()
     20        c = time.clock()
     21        for i in r:
     22            func(*args, **kwargs)
     23        new_time = time.time()
     24        new_clock = time.clock()
     25        times.append(new_time - t)
     26        clocks.append(new_clock - c)
     27    _print_times('Times', times)
     28    _print_times('Clocks', clocks)
     29
     30def _print_times(label, samples):
     31    ss = sorted(samples)
     32    print label
     33    print '  Median: %s' % (ss[len(ss)//2],)
     34    print '  Avg: %s' % (1.0 * sum(ss) / len(ss),)
  • doc/core/benchmarks/defer.py

     
     1from twisted.internet import defer
     2from printtimer import timeit
     3
     4def instantiate():
     5    d = defer.Deferred()
     6
     7def instantiate_shoot_callback():
     8    d = defer.Deferred()
     9    d.callback(1)
     10
     11def instantiate_shoot_errback():
     12    d = defer.Deferred()
     13    try:
     14        1/0
     15    except:
     16        d.errback()
     17    d.addErrback(lambda x: None)
     18
     19def instantiate_add_callbacks_before_result():
     20    d = defer.Deferred()
     21    def f(result):
     22        return result
     23    d.addCallback(f)
     24    d.addErrback(f)
     25    d.addBoth(f)
     26    d.addCallbacks(f)
     27
     28funcs = [
     29    instantiate,
     30    instantiate_shoot_callback,
     31    instantiate_shoot_errback,
     32    instantiate_add_callbacks_before_result,
     33]
     34
     35print defer.Deferred.__module__
     36for func in funcs:
     37    print func
     38    timeit(func, outer_iter=20)