本文整理汇总了Python中timeit.Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例3: main
def main():
t = Timer( 'euler14()', "from __main__ import euler14" )
try:
print t.timeit( 1 )
except:
print t.print_exc()
示例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)
示例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)
示例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
示例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))
示例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)
示例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)
示例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))
示例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)
示例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)))
示例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
示例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)
示例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)))