本文整理汇总了Python中util.Timer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.stop方法的具体用法?Python Timer.stop怎么用?Python Timer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类util.Timer
的用法示例。
在下文中一共展示了Timer.stop方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_POST
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
def do_POST(self):
t = Timer()
t.start()
response = 200
result = {}
try:
content_length = int(self.headers.getheader('content-length'))
req = json.loads(self.rfile.read(content_length))
print req
req_type = req['type']
result = None
if req_type == 'catalog':
result = json.dumps(self.server.catalog)
elif req_type == 'execute':
task = req['args']['task']
json.dumps(BasicExecutor(self.server.cache, task).execute())
elif req_type == 'lookup':
uuid = req['args']['uuid']
result = self.server.cache[uuid]
if type(result) is pd.DataFrame:
page_size = int(req['args']['page_size'])
page_num = int(req['args']['page_num'])
i = page_size * page_num
j = i + page_size
result = result[i:j]
result = result.to_json()
except:
print traceback.format_exc()
response = 500
result = '{}'
t.stop()
self.send_response(response)
self.send_header('Content-type','application/json')
self.end_headers()
self.wfile.write(result)
print 'Run Time:', t.time()
示例2: generate_sudoku
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
def generate_sudoku(self, target = 25):
search = AStarSearch()
base_sudoku = self.generate_full_sudoku()
timer = Timer()
if self.__kind == 'reverse':
problem = ReverseSudokuGenerationProblem(Sudoku(), target, self.solver)
else:
problem = SudokuGenerationProblem(base_sudoku, target, self.solver)
timer.start()
node, cnt_explored = search.search(problem, h = lambda n: problem.value(n.state))
time = timer.stop()
return node.state, len(node.state), cnt_explored, time
示例3: DocTestController
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
#.........这里部分代码省略.........
cumulative wall time: ... seconds
"""
nfiles = 0
nother = 0
for F in self.sources:
if isinstance(F, FileDocTestSource):
nfiles += 1
else:
nother += 1
if self.sources:
filestr = ", ".join(([count_noun(nfiles, "file")] if nfiles else []) +
([count_noun(nother, "other source")] if nother else []))
threads = " using %s threads"%(self.options.nthreads) if self.options.nthreads > 1 else ""
iterations = []
if self.options.global_iterations > 1:
iterations.append("%s global iterations"%(self.options.global_iterations))
if self.options.file_iterations > 1:
iterations.append("%s file iterations"%(self.options.file_iterations))
iterations = ", ".join(iterations)
if iterations:
iterations = " (%s)"%(iterations)
self.log("Doctesting %s%s%s."%(filestr, threads, iterations))
self.reporter = DocTestReporter(self)
self.dispatcher = DocTestDispatcher(self)
N = self.options.global_iterations
for it in range(N):
try:
self.timer = Timer().start()
self.dispatcher.dispatch()
except KeyboardInterrupt:
it = N - 1
break
finally:
self.timer.stop()
self.reporter.finalize()
self.cleanup(it == N - 1)
else:
self.log("No files to doctest")
self.reporter = DictAsObject(dict(error_status=0))
def cleanup(self, final=True):
"""
Runs cleanup activities after actually running doctests.
In particular, saves the stats to disk and closes the logfile.
INPUT:
- ``final`` -- whether to close the logfile
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults, DocTestController
sage: from sage.env import SAGE_SRC
sage: import os
sage: dirname = os.path.join(SAGE_SRC, 'sage', 'rings', 'infinity.py')
sage: DD = DocTestDefaults()
sage: DC = DocTestController(DD, [dirname])
sage: DC.expand_files_into_sources()
sage: DC.sources.sort(key=lambda s:s.basename)
sage: for i, source in enumerate(DC.sources):
....: DC.stats[source.basename] = {'walltime': 0.1*(i+1)}
....:
示例4: DigsbyConnect
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
class DigsbyConnect(TimeoutSocketOne):
_SERVERTIMEOUT = 8
def stale_connection(self):
if getattr(self, '_triumphant', False):
log.info('stale_connection was called but i already won! yayayay')
else:
log.info('%r had a stale connection. Calling do_fail (%r) with a connlost error', self, self.do_fail)
self.do_fail(DigsbyLoginError('connlost'))
def succ(self):
generator = self.do_login()
self._timeouttimer = Timer(self._SERVERTIMEOUT, self.stale_connection)
self._timeouttimer.start()
self.run_sequence( generator )
@lock
def handle_error(self, e=None):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_error(self)
@lock
def handle_expt(self):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_expt(self)
@lock
def handle_close(self):
if hasattr(self, '_timeouttimer'):
self._timeouttimer.stop()
TimeoutSocketOne.handle_close(self)
def do_login(self):
login_str = make_pstring(self.cid) + make_pstring(self.un) + make_pstring(self.password)
codelen = yield (4, login_str)
codelen = unpack('!I', codelen)[0]
if codelen <= 0:
raise DigsbyLoginError('client')
code = yield (codelen, '')
try:
if code == 'success':
cookielen = unpack('!I', (yield (4, '')))[0]
cookie = yield (cookielen, '')
log.debug('Got cookie: %r', cookie)
serverslen = unpack('!I', (yield (4, '')))[0]
servers = yield (serverslen, '')
log.debug('Got servers: %r', servers)
servers = servers.split(' ')
self.cookie = cookie
self.servers = servers
self._triumphant = True
return
elif code == 'error':
log.debug('Got error!')
reasonlen = unpack('!I', (yield (4, '')))[0]
reason = yield (reasonlen, '')
log.debug('Got error reason: %r', reason)
raise DigsbyLoginError(reason)
else:
log.debug('Unknown error occurred! blaming the client!')
raise DigsbyLoginError('client')
except DigsbyLoginError, e:
if e.reason == 'server':
log.debug('Got "upgrading digsby" error code. Sleeping.')
import time; time.sleep(POLL_SLEEP_TIME)
raise e
except Exception, e:
print_exc()
raise DigsbyLoginError('client')
示例5: DocTestController
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
#.........这里部分代码省略.........
cumulative wall time: ... seconds
"""
nfiles = 0
nother = 0
for F in self.sources:
if isinstance(F, FileDocTestSource):
nfiles += 1
else:
nother += 1
if self.sources:
filestr = ", ".join(([count_noun(nfiles, "file")] if nfiles else []) +
([count_noun(nother, "other source")] if nother else []))
threads = " using %s threads"%(self.options.nthreads) if self.options.nthreads > 1 else ""
iterations = []
if self.options.global_iterations > 1:
iterations.append("%s global iterations"%(self.options.global_iterations))
if self.options.file_iterations > 1:
iterations.append("%s file iterations"%(self.options.file_iterations))
iterations = ", ".join(iterations)
if iterations:
iterations = " (%s)"%(iterations)
self.log("Doctesting %s%s%s."%(filestr, threads, iterations))
self.reporter = DocTestReporter(self)
self.dispatcher = DocTestDispatcher(self)
N = self.options.global_iterations
for it in range(N):
try:
self.timer = Timer().start()
self.dispatcher.dispatch()
except KeyboardInterrupt:
it = N - 1
break
finally:
self.timer.stop()
self.reporter.finalize()
self.cleanup(it == N - 1)
else:
self.log("No files to doctest")
self.reporter = DictAsObject(dict(error_status=0))
def cleanup(self, final=True):
"""
Runs cleanup activities after actually running doctests.
In particular, saves the stats to disk and closes the logfile.
INPUT:
- ``final`` -- whether to close the logfile
EXAMPLES::
sage: from sage.doctest.control import DocTestDefaults, DocTestController
sage: import os
sage: dirname = os.path.join(os.environ['SAGE_ROOT'], 'devel', 'sage', 'sage', 'rings', 'infinity.py')
sage: DD = DocTestDefaults()
sage: DC = DocTestController(DD, [dirname])
sage: DC.expand_files_into_sources()
sage: DC.sources.sort(key=lambda s:s.basename)
sage: for i, source in enumerate(DC.sources):
....: DC.stats[source.basename] = {'walltime': 0.1*(i+1)}
....:
sage: DC.run()
示例6: generate_sudoku
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
def generate_sudoku(self, target = 25):
'''
Genera un sudoku rimuovendo casualemente dei valori fino a che non si ottiene un livello di difficoltà pari a quello specificato dal parametro target
Ogni 1000 Backtrack ripristina metà valori scelti casualemente tra quelli rimossi
returns (current_sudoku, len(current_sudoku), cnt_backtrack, time)
'''
base_sudoku = self.generate_full_sudoku()
current_sudoku = Sudoku(base_sudoku.get_dict())
cache = [] # Cache dei valori per il backtrack
cnt_backtrack = 0
cnt_step = 0
single_solution = True;
timer = Timer()
timer.start()
while True:
cnt_step += 1
#print '----------------------------'
#print 'Cache size', len(cache)
# Test di uscita
if len(current_sudoku) == target and single_solution:
break;
#print 'Current values count: ', len(current_sudoku)
#print 'Single solution: ', single_solution
#print 'Backtrack', cnt_backtrack
# Quanti valori togliere
n = len(current_sudoku) / 20
#print 'Prova a rimuovere %d valori' %n
assert n != 0
# Togli i numeri
for i in range(n):
key = random.choice(current_sudoku.filled_cell())
cache.append(key)
current_sudoku.clear_cell(key)
#print 'Cache size', len(cache)
# Verifica l'unicità della soluzione
(sols, b, t) = self.solver.solve(current_sudoku, max_sol = 2)
# Se unica, continua
if len(sols) == 1:
single_solution = True
#print "Rimossi con successo %d elementi" % n
continue
# Se più di una, torna indietro
else:
#print "Backtrack, sols: %d" % len(sols)
single_solution = False
cnt_backtrack += 1
# Ripristina gli ultimi n valori tolti
#print 'Restored cache size', len(cache)
for i in range(n):
# Ripristina gli utlimi elementi tolti
k = cache[-1]
current_sudoku.set_cell(k, base_sudoku.cell(k))
cache.pop(-1)
if cnt_backtrack % 1000 == 0:
#print 'Riprista casualmente metà cache'
for i in range(len(cache)/2):
# Ripristina gli utlimi elementi tolti
idx = random.randint(0, len(cache)-1)
k = cache[idx]
current_sudoku.set_cell(k, base_sudoku.cell(k))
cache.pop(idx)
#print '----------------------------'
#print 'Backtrack necessari: ', cnt_backtrack
time = timer.stop()
return current_sudoku, len(current_sudoku), cnt_step, time
示例7: Executor
# 需要导入模块: from util import Timer [as 别名]
# 或者: from util.Timer import stop [as 别名]
class Executor(Process):
def __init__(self, catalog, results, task):
Process.__init__(self)
self.catalog = catalog
self.results = results
self.task = task
self.timer = Timer()
def get_result(self, uuid):
result = self.results[uuid]
while result.complete == 0.0:
time.sleep(0.0005)
result = self.results[uuid]
return result
def wait(self, uuid):
while self.results[uuid].complete == 0.0:
time.sleep(0.0005)
def run(self):
self.timer.start()
try:
if isinstance(self.task, ClassifyTask):
self.classify()
elif isinstance(self.task, CorrelateTask):
self.correlate()
elif isinstance(self.task, DifferenceTask):
self.difference()
elif isinstance(self.task, FeatureSelectTask):
self.feature_select()
elif isinstance(self.task, FrequentItemsetsTask):
self.frequent_itemsets()
elif isinstance(self.task, IntersectTask):
self.intersect()
elif isinstance(self.task, LoadTask):
self.load()
elif isinstance(self.task, MergeTask):
self.merge()
elif isinstance(self.task, ProjectTask):
self.project()
elif isinstance(self.task, SelectTask):
self.select()
elif isinstance(self.task, UnionTask):
self.union()
else:
raise NotImplementedError()
except Exception as e:
print str(e)
result = ErrorResult(self.task, str(e))
self.results[self.task.uuid] = result
self.timer.stop()
print 'task' + str(self.task.uuid) + ': ' + str(self.timer.time()) + 's'
def classify(self):
raise NotImplementedError()
def correlate(self):
raise NotImplementedError()
def difference(self):
raise NotImplementedError()
def feature_select(self):
raise NotImplementedError()
def frequent_itemsets(self):
raise NotImplementedError()
def intersect(self):
raise NotImplementedError()
def load(self):
raise NotImplementedError()
def merge(self):
raise NotImplementedError()
def project(self):
raise NotImplementedError()
def select(self):
raise NotImplementedError()
def union(self):
raise NotImplementedError()