當前位置: 首頁>>代碼示例>>Python>>正文


Python timeit.Timer方法代碼示例

本文整理匯總了Python中timeit.Timer方法的典型用法代碼示例。如果您正苦於以下問題:Python timeit.Timer方法的具體用法?Python timeit.Timer怎麽用?Python timeit.Timer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在timeit的用法示例。


在下文中一共展示了timeit.Timer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: timer

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def timer(s, v='', nloop=500, nrep=3):
    units = ["s", "ms", "µs", "ns"]
    scaling = [1, 1e3, 1e6, 1e9]
    print("%s : %-50s : " % (v, s), end=' ')
    varnames = ["%ss,nm%ss,%sl,nm%sl" % tuple(x*4) for x in 'xyz']
    setup = 'from __main__ import numpy, ma, %s' % ','.join(varnames)
    Timer = timeit.Timer(stmt=s, setup=setup)
    best = min(Timer.repeat(nrep, nloop)) / nloop
    if best > 0.0:
        order = min(-int(numpy.floor(numpy.log10(best)) // 3), 3)
    else:
        order = 3
    print("%d loops, best of %d: %.*g %s per loop" % (nloop, nrep,
                                                      3,
                                                      best * scaling[order],
                                                      units[order])) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:bench.py

示例2: timeit

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def timeit(self, stmt, setup, number=None):
        self.fake_timer = FakeTimer()
        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
        kwargs = {}
        if number is None:
            number = DEFAULT_NUMBER
        else:
            kwargs['number'] = number
        delta_time = t.timeit(**kwargs)
        self.assertEqual(self.fake_timer.setup_calls, 1)
        self.assertEqual(self.fake_timer.count, number)
        self.assertEqual(delta_time, number)

    # Takes too long to run in debug build.
    #def test_timeit_default_iters(self):
    #    self.timeit(self.fake_stmt, self.fake_setup) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_timeit.py

示例3: repeat

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def repeat(self, stmt, setup, repeat=None, number=None):
        self.fake_timer = FakeTimer()
        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer)
        kwargs = {}
        if repeat is None:
            repeat = DEFAULT_REPEAT
        else:
            kwargs['repeat'] = repeat
        if number is None:
            number = DEFAULT_NUMBER
        else:
            kwargs['number'] = number
        delta_times = t.repeat(**kwargs)
        self.assertEqual(self.fake_timer.setup_calls, repeat)
        self.assertEqual(self.fake_timer.count, repeat * number)
        self.assertEqual(delta_times, repeat * [float(number)])

    # Takes too long to run in debug build.
    #def test_repeat_default(self):
    #    self.repeat(self.fake_stmt, self.fake_setup) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_timeit.py

示例4: timeit_2vector_theano

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def timeit_2vector_theano(init, nb_element=1e6, nb_repeat=3, nb_call=int(1e2), expr="a**2 + b**2 + 2*a*b"):
    t3 = timeit.Timer("tf(av,bv)",
                      """
import theano
import theano.tensor as T
import numexpr as ne
from theano.tensor import exp
%(init)s
av=a
bv=b
a=T.dvector()
b=T.dvector()
tf= theano.function([a,b],%(expr)s)
"""%locals()
)
    ret=t3.repeat(nb_repeat,nb_call)
    return np.asarray(ret) 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:19,代碼來源:gen_graph.py

示例5: timer

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def timer(s, v='', nloop=500, nrep=3):
    units = ["s", "ms", "µs", "ns"]
    scaling = [1, 1e3, 1e6, 1e9]
    print("%s : %-50s : " % (v, s), end=' ')
    varnames = ["%ss,nm%ss,%sl,nm%sl" % tuple(x*4) for x in 'xyz']
    setup = 'from __main__ import numpy, ma, %s' % ','.join(varnames)
    Timer = timeit.Timer(stmt=s, setup=setup)
    best = min(Timer.repeat(nrep, nloop)) / nloop
    if best > 0.0:
        order = min(-int(numpy.floor(numpy.log10(best)) // 3), 3)
    else:
        order = 3
    print("%d loops, best of %d: %.*g %s per loop" % (nloop, nrep,
                                                      3,
                                                      best * scaling[order],
                                                      units[order]))
#    ip.magic('timeit -n%i %s' % (nloop,s)) 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:19,代碼來源:bench.py

示例6: time_training

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def time_training(rep=1):
    w = Workspace(days=1, empty=True)
    set_name = 'mixed_dga_grouped_family_50000_59_0.pkl'
    w.load(set_name, settings.SetTypes.mixed_dga_grouped_family.value)
    dom, lab, _ = w.data_sets_loaded['mixed_dga_grouped_family_50000_59_0.pkl'].expand()

    svm = SVMClassifier(dga='mix')
    t = Timer(lambda:  svm.training(dom, lab))
    print('SVM Training: ' + str(t.timeit(number=rep)))

    rf = RFClassifier(dga='mix')
    t = Timer(lambda:  rf.training(dom, lab))
    print('RF Training: ' + str(t.timeit(number=rep)))

    set_name = 'mixed_dga_grouped_family_50000_59_1.pkl'
    w.load(set_name, settings.SetTypes.mixed_dga_grouped_family.value)
    dom, lab, _ = w.data_sets_loaded['mixed_dga_grouped_family_50000_59_1.pkl'].expand()

    t = Timer(lambda:  svm.predict(dom, lab))
    print('SVM Classify: ' + str(t.timeit(number=rep)))

    t = Timer(lambda: rf.predict(dom, lab))
    print('RF Classify: ' + str(t.timeit(number=rep))) 
開發者ID:fanci-dga-detection,項目名稱:fanci,代碼行數:25,代碼來源:main_helper.py

示例7: run

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def run(engines, number=2000, verbose=False):
    basepath = os.path.abspath(os.path.dirname(__file__))
    for engine in engines:
        dirname = os.path.join(basepath, engine)
        if verbose:
            print('%s:' % engine.capitalize())
            print('--------------------------------------------------------')
        else:
            sys.stdout.write('%s:' % engine.capitalize())
        t = timeit.Timer(setup='from __main__ import %s; render = %s(r"%s", %s)'
                                       % (engine, engine, dirname, verbose),
                                 stmt='render()')

        time = t.timeit(number=number) / number
        if verbose:
            print('--------------------------------------------------------')
        print('%.2f ms' % (1000 * time))
        if verbose:
            print('--------------------------------------------------------') 
開發者ID:sqlalchemy,項目名稱:mako,代碼行數:21,代碼來源:basic.py

示例8: timeit

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def timeit(self, stmt, setup, number=None, globals=None):
        self.fake_timer = FakeTimer()
        t = timeit.Timer(stmt=stmt, setup=setup, timer=self.fake_timer,
                globals=globals)
        kwargs = {}
        if number is None:
            number = DEFAULT_NUMBER
        else:
            kwargs['number'] = number
        delta_time = t.timeit(**kwargs)
        self.assertEqual(self.fake_timer.setup_calls, 1)
        self.assertEqual(self.fake_timer.count, number)
        self.assertEqual(delta_time, number)

    # Takes too long to run in debug build.
    #def test_timeit_default_iters(self):
    #    self.timeit(self.fake_stmt, self.fake_setup) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:test_timeit.py

示例9: run

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def run(which=None, number=10):
    tests = ['test_builder', 'test_genshi',
             'test_genshi_text',
             'test_genshi_builder', 'test_mako', 'test_kid', 'test_kid_et',
             'test_et', 'test_cet', 'test_clearsilver', 'test_django',
             'test_cheetah',
             'test_spitfire', 'test_spitfire_o1',
             'test_spitfire_o2', 'test_spitfire_o3',
             'test_python_stringio', 'test_python_cstringio', 'test_python_array'
             ]

    if which:
        tests = filter(lambda n: n[5:] in which, tests)

    for test in [t for t in tests if hasattr(sys.modules[__name__], t)]:
        t = timeit.Timer(setup='from __main__ import %s;' % test,
                         stmt='%s()' % test)
        time = t.timeit(number=number) / number

        if time < 0.00001:
            result = '   (not installed?)'
        else:
            result = '%16.2f ms' % (1000 * time)
        print '%-35s %s' % (getattr(sys.modules[__name__], test).__doc__, result) 
開發者ID:youtube,項目名稱:spitfire,代碼行數:26,代碼來源:bigtable.py

示例10: time_fn

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def time_fn(label, fn, arg):
    if hasattr(arg, '__len__') and len(arg) == 2:
        v, f = arg
        print 'Timing %s - %s(%s, %s)' % (label, fn.__name__, v, f.__name__)
        t = timeit.Timer(lambda: fn(v, f))
    else:
        print 'Timing %s - %s(%s)' % (label, fn.__name__, arg)
        t = timeit.Timer(lambda: fn(arg))
    try:
        r = t.repeat(10, 100000)
    except:  # pylint:disable=bare-except
        t.print_exc()
        return

    best = min(r)
    scale = 1e3 / len(r)
    msec = best * scale
    all = ', '.join('%.1f' % (v * scale) for v in r)
    print 'best run: %.1f msec per loop [%s]' % (msec, all) 
開發者ID:youtube,項目名稱:spitfire,代碼行數:21,代碼來源:filter_function_benchmark.py

示例11: time_particlescalars

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def time_particlescalars():
    import postpic as pp
    import timeit
    pp.chooseCode('dummy')
    dr1 = pp.readDump(0.01e6, dimensions=3)
    dr2 = pp.readDump(1.0e6, dimensions=3)
    ms1 = pp.MultiSpecies(dr1, 'electron')
    ms2 = pp.MultiSpecies(dr2, 'electron')
    testexprs = ['x', 'x + y + z', 'gamma', 'beta', 'angle_xy', 'angle_xaxis',
                'sqrt(x**2 + y**2 + z**2)', 'r_xyz',
                '(gamma > 1.5) & (angle_xaxis < 0.2) & (r_xyz < 2)']
    print('')
    print('calculation times for n million particles, averaged over 3 calculations each...')
    headformat = ' {:2s}  | {:6s} | {:6s} | {:s}'
    print(headformat.format('n', ' t', ' t/n', 'per particle quantity'))
    print(headformat.format('',   ' ms', 'ms/mio', ''))
    def timeexpr(expr, ms):
        t = timeit.Timer(lambda: ms(expr))
        tc = t.timeit(number=3)/3.0
        npartmio = len(ms)/1e6
        print('{:4.2f} | {:6.2f} | {:6.2f} | "{}"'.format(npartmio, tc*1e3, (tc*1e3)/npartmio, expr))
    for expr in testexprs:
        for ms in (ms1, ms2):
            timeexpr(expr, ms) 
開發者ID:skuschel,項目名稱:postpic,代碼行數:26,代碼來源:time_cythonfunctions.py

示例12: get_timeit

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def get_timeit(self, setup):
        return min(timeit.Timer(
            'for n in range(64, 10000): sample_n_k(n, 64)',
            setup=setup).  repeat(repeat=10, number=1)) 
開發者ID:chainer,項目名稱:chainerrl,代碼行數:6,代碼來源:test_random.py

示例13: main

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def main():
    parse_command_line()
    if options.dump:
        print(tmpl.code)
        sys.exit(0)
    t = Timer(render)
    results = t.timeit(options.num) / options.num
    print('%0.3f ms per iteration' % (results*1000)) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:10,代碼來源:template_benchmark.py

示例14: main

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def main():
    parse_command_line()
    t = Timer(e1)
    results = t.timeit(options.num) / options.num
    print('engine: %0.3f ms per iteration' % (results * 1000))
    t = Timer(c1)
    results = t.timeit(options.num) / options.num
    print('coroutine: %0.3f ms per iteration' % (results * 1000)) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:10,代碼來源:gen_benchmark.py

示例15: _test

# 需要導入模塊: import timeit [as 別名]
# 或者: from timeit import Timer [as 別名]
def _test(idx, size, stars, noise, seed, images_seed, repeats):

    # create the two images
    source, target = get_images(
        size=size, stars=stars, noise=noise, seed=images_seed)

    # create the timer
    test_globals = {"aa": aa, "source": source, "target": target}
    timer = timeit.Timer(stmt=STATEMENT, globals=test_globals)

    # find the number of loops
    loops = timer.autorange()[0]

    # create a copy of the params to be returned ad result
    result = OrderedDict({
        "idx": idx, "size": size, "noise": noise, "stars": stars, "seed": seed,
        "images_seed": images_seed, "repeats": repeats, "loops": loops})

    # execute the timeit
    times = timer.repeat(repeats, loops)

    # store the times into the result
    result["time"] = np.min(np.array(times) / loops)
    for tidx, time in enumerate(times):
        result[f"time_{tidx}"] = time

    return result 
開發者ID:toros-astro,項目名稱:astroalign,代碼行數:29,代碼來源:time_bench.py


注:本文中的timeit.Timer方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。