本文整理汇总了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]))
示例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)
示例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)
示例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)
示例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))
示例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)))
示例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('--------------------------------------------------------')
示例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)
示例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)
示例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)
示例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)
示例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))
示例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))
示例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))
示例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