本文整理汇总了Python中timeit.Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: parser
def parser(self, path, articles, vocabulary):
doc = fileinput.input(path)
campo_aux = ""
query = None
for line in doc:
i = 0
campo = line[:2]
if (campo == "QN"):
if (query != None):
t = Timer(lambda: query.make_rank(articles, vocabulary))
t = t.timeit(number=1)
self.time = self.time + t
query.metrics(self)
print("Tempo para criar rank e ordenar", t)
query = Query()
line = re.sub("^" + campo, "", line)
query.campos_dic["QN"](line)
continue
if (campo in Query.campos):
campo_aux = str(campo)
line = re.sub("^" + campo, "", line)
query.campos_dic[campo](line)
else:
query.campos_dic[campo_aux](line)
t = Timer(lambda: query.make_rank(articles, vocabulary))
t = t.timeit(number=1)
self.time = self.time + t
query.metrics(self)
print("Tempo para criar rank e ordenar", t)
开发者ID:daniel12fsp,项目名称:trab_modelo_vetorial,代码行数:32,代码来源:vector_model-Daniel.py
示例2: main
def main():
benchmarks = {}
# Run all of the performance comparisons.
for testname, method in tests.items():
benchmarks[testname] = {}
results = [None, None]
for i, module in enumerate((re, re2)):
# We pre-compile the pattern, because that's
# what people do.
current_re[0] = module.compile(method.pattern)
results[i] = method(current_re[0], **method.data)
# Run a test.
t = Timer("test(current_re[0],**test.data)", setup_code % testname)
benchmarks[testname][module.__name__] = (
t.timeit(method.num_runs),
method.__doc__.strip(),
method.pattern,
method.num_runs,
)
if results[0] != results[1]:
raise ValueError("re2 output is not the same as re output: %s" % testname)
benchmarks_to_ReST(benchmarks)
开发者ID:alec,项目名称:pyre2,代码行数:26,代码来源:performance.py
示例3: main
def main():
t = Timer( 'euler14()', "from __main__ import euler14" )
try:
print t.timeit( 1 )
except:
print t.print_exc()
开发者ID:JeroenDeDauw,项目名称:ProjectEuler,代码行数:7,代码来源:p14.py
示例4: evaluateRunTime
def evaluateRunTime():
global SDStr
from timeit import Timer
for SDL in SDStr:
print( SDL)
t1 = Timer("Shudu(\"%s\").scanSDL()" % SDL, "from __main__ import Shudu")
print( sum(t1.repeat(10, 1))/10)
开发者ID:dinimicky,项目名称:py_arith,代码行数:7,代码来源:shudu2.py
示例5: performance_experiment
def performance_experiment(use_rls):
used_method = 'rls' if use_rls else 'svm'
data = load_metz_data()
split_data = leave_both_rows_and_columns_out_cv(*data)
outer_iter = 500
inner_iters = [1] if use_rls else [1, 10, 100]
reg_param_range = [-7, -2, 0, 2, 7, 9] # range(-15, 16)
reg_params = [('0', 0)] + map(lambda x: ('2^{0}'.format(x), 2**x), reg_param_range)
for inner_iter in inner_iters:
all_results = []
for reg_param in reg_params:
results = []
params = split_data + (perfmeasure, reg_param[1], use_rls, outer_iter, inner_iter)
timer_with_lambda = Timer(
lambda: results.extend(single_holdout(*params)))
lambda_perf = timer_with_lambda.timeit(number=1)
print ('With {0} outer loops and {1} inner loops, the algorithm took in total {2} seconds. Regularization parameter {3}.'
.format(outer_iter, inner_iter, lambda_perf, reg_param[0]))
print 'Results were {0}.'.format(results)
print results
all_results.append((results, reg_param[0]))
plot_name = '{0}'.format(used_method) if use_rls else '{0}-iterations={1}'.format(used_method, inner_iter)
create_plot(plot_name, all_results)
开发者ID:ajairo,项目名称:kron_experiments,代码行数:25,代码来源:kron_experiment_Metz_CG.py
示例6: getTimeOfNumpyStatements
def getTimeOfNumpyStatements(statement, number=1):
t = Timer(DictionaryStatements[statement], setup="import numpy as np")
sumAllLoopsTiming = t.timeit(number=number)
avgTimePerLoopUsec = (sumAllLoopsTiming / number)
# TODO: if preferred, may use repeat and get the best result with min func
return avgTimePerLoopUsec
开发者ID:datascience-js,项目名称:compare-performance-math-libs-tool,代码行数:7,代码来源:profileNumpy.py
示例7: main
def main():
parser = argparse.ArgumentParser(description='Wrapper for Project Euler problems.')
parser.add_argument('filename', metavar='FILE', help='Name of the file to run.')
parser.add_argument('-q', dest='display_question', action='store_true', default=False, help='If present, displays the question.')
parser.add_argument('-x', dest='no_output', action='store_true', default=False, help='If present, does not execute the question.')
parser.add_argument('-t', dest='time_it', action='store_true', default=False, help='If prsent, measure the average execution time.')
args = parser.parse_args()
question = imp.load_source('question', args.filename)
q_main = question.main
if args.display_question:
print q_main.__doc__
if args.no_output:
return
print(q_main())
if args.time_it:
times = 1000 # How to set default, or value if flag present?
print times
from timeit import Timer
t = Timer(lambda: q_main())
print('{seconds} s to execute {number} times'.format(seconds=t.timeit(number=times),number=times))
开发者ID:nt3rp,项目名称:Project-Euler,代码行数:27,代码来源:run.py
示例8: performance_test
def performance_test():
""" Run test for the given data to test system performance.
(This is used for developing optimisations)
"""
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit(number=1)
开发者ID:alyoung,项目名称:django-dms,代码行数:7,代码来源:friendly_id.py
示例9: test_prime_pairs
def test_prime_pairs(times, combi_size):
global t
t = Timer(
"[prime_pairs(combi,%d) for combi in combinations(xrange(100))]" % combi_size,
"from __main__ import prime_pairs; from itertools import combinations",
)
print t.timeit(1)
开发者ID:ehudt,项目名称:euler,代码行数:7,代码来源:test_prime_pairs.py
示例10: run
def run(self):
"""Run tests."""
test_runs = 100
for func in [self.all_func, self.only_id, self.few_func]:
self.reset()
t = Timer(func)
print(t.timeit(number=test_runs))
开发者ID:zcomx,项目名称:zcomix.com,代码行数:7,代码来源:dal_benchmarks.py
示例11: test_time_read_line
def test_time_read_line(self):
"""Test to see if continuous read of analog data is less than two secounds per call"""
self.port.upload_code(self.pde_hex_path)
t = Timer(lambda: self.port.read_line())
time = t.timeit(1)
print time
self.assert_(time < 2)
开发者ID:gusfeiysu,项目名称:Python-Arduino-Unit-Testing,代码行数:7,代码来源:test_arduino_analog_speed.py
示例12: time_impls
def time_impls():
runs = 1000
solvers = [p2_recursive, p2_iterative_generator, p2_recursive_generator, p2_primitve]
for solver in solvers:
t = Timer(solver)
assert solver() == 4613732
print("%d runs of %s solved in %f seconds" % (runs, solver.__name__, t.timeit(number=1000)))
开发者ID:piohhmy,项目名称:euler,代码行数:7,代码来源:p002.py
示例13: get_closest_region
def get_closest_region(service="ec2", repetitions=1):
"""
Get the closest region for a particular service based on its average response time.
:type service: str
:param service: The service to attempt a connection to. By default, this is ``ec2``.
:type repetitions: int
:param repetitions: The number of measurements to take before calculating an average.
"""
regions = [
region.name
for region in regioninfo.get_regions(service)
if "gov" not in region.name and "cn" not in region.name
]
latency = {}
for region in regions:
connection = Timer(
"h.request('GET', '/')",
"from http.client import HTTPSConnection; h=HTTPSConnection('%s.%s.amazonaws.com')" % (service, region),
)
times = connection.repeat(repetitions, 1)
avg_latency = sum(times) / float(len(times))
latency[region] = avg_latency
logger.info("Average latency to Amazon %s %s is %s" % (service.upper(), region, latency[region]))
region = min(latency, key=latency.get)
return region
开发者ID:thsteinmetz,项目名称:skyrocket,代码行数:31,代码来源:utils.py
示例14: test2a_timing
def test2a_timing(self):
"""Test timing for two functions"""
print "test2a_timing(): timings in msec/iter"
for sz in self.sz_l[:1]:
for spsz in self.spotsz_l:
for pos in self.pos_l:
setup_str = """
from __main__ import gauss, _gauss_slow
import numpy as np
sz = (%d,%d)
spsz = %g
pos = (%d,%d)
amp = %g
noi = %g
""" % (
sz + (spsz,) + pos + (self.amp, self.noi)
)
t1 = Timer(
"""
g=_gauss_slow(sz, spsz, pos, amp, noi)
""",
setup_str,
)
t2 = Timer(
"""
a=gauss(sz, spsz, pos, amp, noi)
""",
setup_str,
)
t_g1 = 1000 * min(t1.repeat(3, self.niter)) / self.niter
t_g2 = 1000 * min(t2.repeat(3, self.niter)) / self.niter
print "test2a_timing(): sz:", sz, "g1: %.3g, g2: %.3g, speedup: %.3g" % (t_g1, t_g2, t_g1 / t_g2)
开发者ID:tvwerkhoven,项目名称:libtim-py,代码行数:33,代码来源:test_xcorr.py
示例15: use_pooling
def use_pooling():
"""Process 10 random_wait calls 5 at a time"""
def pooled():
with Pool(5) as pool:
pool.map(random_wait, range(10))
t = Timer(lambda: pooled())
print('{:.5f} seconds'.format(t.timeit(number=1)))
开发者ID:orlandopython,项目名称:Python-Fundamentals,代码行数:7,代码来源:tipstricks.py
示例16: test3a_timing_calc
def test3a_timing_calc(self):
"""Test Zernike calculation timing and cache functioning"""
t1 = Timer("""
a=calc_zernike(vec, rad, z_cache)
""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
z_cache = {}
""" % (self.rad, self.nmodes) )
t2 = Timer("""
a=calc_zernike(vec, rad, {})
""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
""" % (self.rad, self.nmodes) )
t_cache = t1.timeit(self.calc_iter)/self.calc_iter
t_nocache = t2.timeit(self.calc_iter)/self.calc_iter
# Caching should be at least twice as fast as no caching
# Note that here we do not initialize the cache in the setup, it is
# set to an empty dict which is filled on first run. This test should
# test that this automatic filling works properly
self.assertGreater(t_nocache/2.0, t_cache)
开发者ID:Anirudh257,项目名称:libtim-py,代码行数:29,代码来源:test_zern.py
示例17: main
def main():
global scene
print('Reading \'{}\'...'.format(path))
t = Timer(doImport)
secs = t.timeit(1)
print('> On AssimpCy Took {:0.4f} seconds.'.format(secs))
print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes,
scene.mNumTextures,
scene.mNumMaterials,
scene.mNumAnimations))
if scene.HasMeshes and scene.mMeshes[0].HasPositions:
print('\tand {} vertices on mesh 0'.format(int(scene.mMeshes[0].mNumVertices)))
v = int(scene.mMeshes[0].mNumVertices / 2)
print('\tVertex {} = {}'.format(v, scene.mMeshes[0].mVertices[v]))
print()
# print(scene.mRootNode.mTransformation)
t = Timer(doImportPy)
secs = t.timeit(1)
print('> On PyAssimp Took {:0.4f} seconds.'.format(secs))
print('\tHas {} meshes, {} textures, {} materials, {} animations'.format(scene.mNumMeshes,
scene.mNumTextures,
scene.mNumMaterials,
scene.mNumAnimations))
if len(scene.meshes) and len(scene.meshes[0].vertices):
print('\tand {} vertices on mesh 0'.format(len(scene.meshes[0].vertices)))
v = int(len(scene.meshes[0].vertices) / 2)
print('\tVertex {} = {}'.format(v, scene.meshes[0].vertices[v]))
# print(scene.rootnode.transformation)
release(scene)
开发者ID:jr-garcia,项目名称:AssimpCy,代码行数:32,代码来源:vs_test.py
示例18: test3b_timing_calc
def test3b_timing_calc(self):
"""Test Zernike calculation performance with and without cache, print results"""
t1 = Timer("""
a=calc_zernike(vec, rad, z_cache)
""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
z_cache = calc_zern_basis(len(vec), rad)
""" % (self.rad, self.nmodes) )
t2 = Timer("""
a=calc_zernike(vec, rad, {})
""", """
from zern import calc_zern_basis, fit_zernike, calc_zernike
import numpy as np
rad = %d
nmodes = %d
vec = np.random.random(nmodes)
""" % (self.rad, self.nmodes) )
t_cached = min(t1.repeat(2, self.calc_iter))/self.calc_iter
t_nocache = min(t2.repeat(2, self.calc_iter))/self.calc_iter
print "test3b_timing_calc(): rad=257, nmodes=25 cache: %.3g s/it no cache: %.3g s/it" % (t_cached, t_nocache)
开发者ID:Anirudh257,项目名称:libtim-py,代码行数:27,代码来源:test_zern.py
示例19: act_as_baboon
def act_as_baboon(bid, init_side):
global avg_time
import random
rng = random.Random()
rng.seed(bid)
random = rng.random()
def time_cross():
side = init_side
count = 0
while count < num_cross:
with turnstile:
switches[side].lock(rope)
with multiplex:
sleep(random) # simulate crossing
switches[side].unlock(rope)
side = 1 - side
count += 1
timer = Timer(time_cross)
time = timer.timeit(1)
with mutex:
avg_time += time
print('Baboon {} finished in {:0.3f}s'.format(bid, time))
开发者ID:emarcha,项目名称:college-coursework,代码行数:25,代码来源:baboons_v1.py
示例20: exe_time
def exe_time(func_name, min_num, max_num):
"""Execute the function.
-------------------------------------------------------
exe_time(func_name, min_num, max_num):
-------------------------------------------------------
Input:
func_name -- the function the complexity of whic is
going to be measured. The function must
only take one integer as parameter.
min_num -- min possible value for the parameter.
max_num -- max possible value for the parameter.
-------------------------------------------------------
Output:
nlist -- a list of integers was tried
tlist -- a list of execution time for each
integer in nlist
-------------------------------------------------------
"""
class wrapper(object):
def __init__(self, n):
self.para = n
def __call__(self):
return func_name(self.para)
nlist = numpy.linspace(min_num, max_num, 10).astype('int64')
tlist = numpy.empty(10)
for i, n in enumerate(nlist):
timer = Timer(wrapper(n))
tlist[i] = timer.timeit(10000)
return nlist, tlist
开发者ID:GunioRobot,项目名称:The-Basic-of-The-Basic,代码行数:31,代码来源:big_O.py
注:本文中的timeit.Timer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论