本文整理汇总了Python中time.time函数的典型用法代码示例。如果您正苦于以下问题:Python time函数的具体用法?Python time怎么用?Python time使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了time函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: time
def time(self, name):
rt = RunTimer()
before = time.time()
yield rt # Can call .set_result()
after = time.time()
elapsed = after - before
self.log(name, "in {0:.2f} secs".format(elapsed), rt.result)
示例2: train
def train(self, x, y, param_names, **kwargs):
start = time.time()
scaled_x = self._set_and_preprocess(x=x, param_names=param_names)
# Check that each input is between 0 and 1
self._check_scaling(scaled_x=scaled_x)
if self._debug:
print "Shape of training data: ", scaled_x.shape
print "Param names: ", self._used_param_names
print "First training sample\n", scaled_x[0]
print "Encode: ", self._encode
# Do a random search
max_features, learning_rate, max_depth, min_samples_leaf, n_estimators = self._random_search(random_iter=100,
x=scaled_x, y=y)
# Now train model
gb = GradientBoostingRegressor(loss='ls',
learning_rate=learning_rate,
n_estimators=n_estimators,
subsample=1.0,
min_samples_split=2,
min_samples_leaf=min_samples_leaf,
max_depth=max_depth,
init=None,
random_state=self._rng,
max_features=max_features,
alpha=0.9,
verbose=0)
gb.fit(scaled_x, y)
self._model = gb
duration = time.time() - start
self._training_finished = True
return duration
示例3: perform
def perform(self, node, inputs, output_storage):
start_time = time.time()
log_posteriors, seq_lengths = inputs
if numpy.isnan(log_posteriors).any():
print >> log.v1, 'SprintErrorSigOp: log_posteriors contain NaN!'
if numpy.isinf(log_posteriors).any():
print >> log.v1, 'SprintErrorSigOp: log_posteriors contain Inf!'
#numpy.set_printoptions(threshold=numpy.nan)
print >> log.v1, 'SprintErrorSigOp: log_posteriors:', log_posteriors
if self.sprint_instance_pool is None:
print >> log.v3, "SprintErrorSigOp: Starting Sprint %r" % self.sprint_opts
self.sprint_instance_pool = SprintInstancePool.get_global_instance(sprint_opts=self.sprint_opts)
loss, errsig = self.sprint_instance_pool.get_batch_loss_and_error_signal(log_posteriors, seq_lengths)
#print >> log.v4, 'loss:', loss, 'errsig:', errsig
output_storage[0][0] = loss
output_storage[1][0] = errsig
print >> log.v5, 'SprintErrorSigOp: avg frame loss for segments:', loss.sum() / seq_lengths.sum()
end_time = time.time()
if self.debug_perform_time is None:
from Config import get_global_config
config = get_global_config()
self.debug_perform_time = config.bool("debug_SprintErrorSigOp_perform_time", False)
if self.debug_perform_time:
print >>log.v1, "SprintErrorSigOp perform time:", end_time - start_time
from Device import deviceInstance
assert deviceInstance.is_device_proc()
forward_time = start_time - deviceInstance.compute_start_time
print >> log.v1, "SprintErrorSigOp forward time:", forward_time
示例4: run
def run(clients, servers, startup=10):
port = 10000
server_procs = []
for server in servers:
print "starting", server
proc = subprocess.Popen([sys.executable, server, str(port)], stdout=subprocess.PIPE)
_PROCS.append(proc)
server_procs.append(proc)
proc.port = port
proc.server_name = server
start = time.time()
while time.time() - start < startup:
try:
socket.create_connection( ('localhost', port))
break
except socket.error:
pass
else: # didn't break
raise EnvironmentError(
"server {0} on port {1} didn't come ready within {2}s".format(
server, port, startup))
port += 1
for serv in server_procs:
print "SERVER", serv.server_name
for client in clients:
print " CLIENT", client.__name__, client(serv.port)
serv.kill()
示例5: add_engines
def add_engines(n=1, profile='iptest', total=False):
"""add a number of engines to a given profile.
If total is True, then already running engines are counted, and only
the additional engines necessary (if any) are started.
"""
rc = Client(profile=profile)
base = len(rc)
if total:
n = max(n - base, 0)
eps = []
for i in range(n):
ep = TestProcessLauncher()
ep.cmd_and_args = ipengine_cmd_argv + [
'--profile=%s' % profile,
'--InteractiveShell.colors=nocolor'
]
ep.start()
launchers.append(ep)
eps.append(ep)
tic = time.time()
while len(rc) < base+n:
if any([ ep.poll() is not None for ep in eps ]):
raise RuntimeError("A test engine failed to start.")
elif time.time()-tic > 15:
raise RuntimeError("Timeout waiting for engines to connect.")
time.sleep(.1)
rc.close()
return eps
示例6: readData
def readData():
global rdObj
rdObj.hostTemp = get_temperature()
for i in range(60):
timebegin = time.time()
get_per_sec_info()
time.sleep(1-(time.time()-timebegin))
示例7: find_proxy
def find_proxy( url, timeout, testing_url):
try:
response = urllib.urlopen( url )
except:
if Debug: print "Request to get proxy failed."
return (False, False)
result=response.getcode()
content = response.read()
data = json.loads( content )
if Debug: print data['curl']
start_time = time.time()
try:
response = urllib.urlopen(testing_url, proxies={'http':data['curl']})
except:
if Debug: print "Proxy test request failed."
return (False, False)
result=response.getcode()
request_time = time.time() - start_time
if result == 200:
if Debug: print "\n\nGot test url with %d in %f seconds" % (result, request_time)
return (data['curl'], request_time)
else:
if Debug: print "Failed with %d" % result
return (False, False)
示例8: wait_for_completion
def wait_for_completion(self):
if self.is_old:
self.old.wait_for_completion()
return
end = time.time() + self.timeout
while db.guest_get_status(self.task_id) == "running":
log.debug("%s: analysis still processing", self.vmid)
time.sleep(1)
# If the analysis hits the critical timeout, just return straight
# away and try to recover the analysis results from the guest.
if time.time() > end:
raise CuckooGuestError(
"The analysis hit the critical timeout, terminating.")
try:
status = self.get("/status", timeout=5).json()
except Exception as e:
log.info("Virtual Machine /status failed (%r)", e)
# this might fail due to timeouts or just temporary network issues
# thus we don't want to abort the analysis just yet and wait for things to
# recover
continue
if status["status"] == "complete":
log.info("%s: analysis completed successfully", self.vmid)
return
elif status["status"] == "exception":
log.info("%s: analysis caught an exception\n%s", self.vmid,
status["description"])
return
示例9: simple_find_in_context
def simple_find_in_context(self, ref, context):
"""
Like simple_find, but limits the search to a specific context. Useful
for when you want to (e.g.) make sure you only look in the webview.
:param ref: an identifier for an element; id, class name, partial link text, etc.
:param context: the context in which we're looking; typically WEBVIEW or NATIVE_APP
:rtype: WebElement
"""
# speed up the implicit wait, because with default time, this takes way
# too long because of all the possible permutations
self.implicitly_wait(HackedWebDriver.QuickImplicitWait_sec)
# wrap this all in a try so we can restore the default implicit wait if
# and when this block exits
try:
timeout = time.time() + self.MaxSmartSearchTime_sec
while time.time() < timeout:
element = self._simple_find_core(ref, context)
if element:
return element
log.debug(u'exhausted all search methods, looping until we timeout here')
finally:
# restore the default implicit wait
self.implicitly_wait(HackedWebDriver.ImplicitWait_sec)
assert False, u'couldnt find {}!'.format(ref)
示例10: update_follower2leveldb
def update_follower2leveldb():
# 从leveldb更新leveldb的用户粉丝数数据
# test 0.15 seconds per 10000 users, total 22670000 users, 0.09 h
users = xapian_search_user.iter_all_docs(fields=['user', 'followers_count'])
count = 0
ts = te = time.time()
for k, v in user_followers_count_leveldb.RangeIter():
uid = int(k)
follower = int(v)
try:
active, important, _follower, domain = daily_identify_aifd_bucket.Get(str(uid)).split('_')
except KeyError:
active = 0
important = 0
domain = 20
daily_identify_aifd_bucket.Put(str(uid), str(active) + '_' + str(important) + '_' + \
str(follower) + '_' + str(domain))
if count % 10000 == 0:
te = time.time()
print count, '%s sec' % (te - ts), ' identify person follower', now_datestr
ts = te
count += 1
示例11: update_domain2leveldb
def update_domain2leveldb():
# 从leveldb更新leveldb的用户领域所属数据
# test 0.15 seconds per 10000 users, total 22670000 users, 0.09 h
count = 0
ts = te = time.time()
for k, v in domain_leveldb.RangeIter():
uid, datestr = k.split('_')
domainid = DOMAIN_LIST.index(v)
try:
active, important, follower, _domain = daily_identify_aifd_bucket.Get(str(uid)).split('_')
except KeyError:
active = 0
important = 0
follower = 0
domain = domainid
daily_identify_aifd_bucket.Put(str(uid), str(active) + '_' + str(important) + '_' + \
str(follower) + '_' + str(domain))
if count % 10000 == 0:
te = time.time()
print count, '%s sec' % (te - ts), ' identify person domain', now_datestr
ts = te
count += 1
示例12: main
def main():
# Process CLI arguments.
try:
execname, host, port, mode = sys.argv
except ValueError:
execname = sys.argv[0]
print >>sys.stderr, '%s: incorrect number of arguments' % execname
print >>sys.stderr, 'usage: %s hostname port [sit|const|wild]' % sys.argv[0]
sys.exit(-1)
bzrc = BZRC(host, int(port))
cur_time = time.time()
agent = PigeonAgent(bzrc, mode, cur_time)
# Run the agent
try:
while True:
cur_time = time.time()
agent.behave(cur_time)
except KeyboardInterrupt:
print "Exiting due to keyboard interrupt."
agent.stop()
bzrc.close()
示例13: main
def main():
print("Code to look at runtime for insertion sort vs. Python's list sort.")
numDig = 5 #number of digits to output
#large list with numElements elements
numElements = 10000
data = []
for i in range(numElements):
data.append(randint(1, numElements))
print("\nSorting list with " + str(len(data)) + " elements.\n")
start = time.time()
insertionSort(data)
end = time.time()
print("Insertion sort -> " + str(round(end - start, numDig)) + " seconds.")
#large list with numElements elements
numElements = 10000
data = []
for i in range(numElements):
data.append(randint(1, numElements))
start = time.time()
data.sort()
end = time.time()
print("Python's sort -> " + str(round(end - start, numDig)) + " seconds.")
示例14: testFolder
def testFolder(inputfolder, outputfolder, decisionThreshold = cfg.decision_threshold, applyNMS=True):
fileList = os.listdir(inputfolder)
imagesList = filter(lambda element: '.jpg' in element, fileList)
print 'Start processing '+inputfolder
start = time()
for filename in imagesList:
imagepath = inputfolder + '/' + filename
print 'Processing '+imagepath
#Test the current image
bboxes, scores = testImage(imagepath, decisionThreshold=decisionThreshold, applyNMS=applyNMS)
#Store the result in a dictionary
result = dict()
result['imagepath'] = imagepath
result['bboxes'] = bboxes
result['scores'] = scores
#Save the features to a file using pickle
outputFile = open(outputfolder+'/'+filename+'_'+'-'.join(cfg.featuresToExtract)+'_'+cfg.model+'.results', "wb")
pickle.dump(result, outputFile)
outputFile.close()
elapsed_time = time() - start
print('Time elapsed using regular function: ', elapsed_time)
示例15: attach_volume
def attach_volume(self, local_dev_timeout=120):
new_device_name = None
if not self.volume:
raise FailureWithCode('This import does not have a volume', INPUT_DATA_FAILURE)
instance_id = self.instance_id
devices_before = get_block_devices()
device_name = self.next_device_name(devices_before)
log.debug('Attaching volume {0} to {1} as {2}'.
format(self.volume.id, instance_id, device_name), self.task_id)
self.ec2_conn.attach_volume_and_wait(self.volume.id,
instance_id,
device_name)
elapsed = 0
start = time.time()
while elapsed < local_dev_timeout and not new_device_name:
new_block_devices = get_block_devices()
log.debug('Waiting for local dev for volume: "{0}", '
'elapsed:{1}'.format(self.volume.id, elapsed), self.task_id)
diff_list = list(set(new_block_devices) - set(devices_before))
if diff_list:
for dev in diff_list:
# If this is virtio attempt to verify vol to dev mapping
# using serial number field info
if not os.path.basename(dev).startswith('vd'):
try:
self.verify_virtio_volume_block_device(
volume_id=self.volume.id,
blockdev=dev)
except ValueError, ex:
raise FailureWithCode(ex, ATTACH_VOLUME_FAILURE)
new_device_name = dev
break
elapsed = time.time() - start
if elapsed < local_dev_timeout:
time.sleep(2)