本文整理汇总了Python中time.time.time函数的典型用法代码示例。如果您正苦于以下问题:Python time函数的具体用法?Python time怎么用?Python time使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了time函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _pack_message
def _pack_message(self,device = None):
addresses = (device or [self.device_token])
deliver_before_timestamp = (datetime.now() + (5 * 60))
push_id = int(round(int(time.time()) * random()) + int(time.time())) # simplify
t = get_template("bbpush.post")
c = Context({'addresses':addresses,'deliver_before_timestamp':deliver_before_timestamp ,'push_id':push_id,'app_id':settings.BB_APP_ID})
content = t.render(c)
开发者ID:Jaromudr,项目名称:django-pushnotification,代码行数:7,代码来源:bbpush.py
示例2: buffer_newevents
def buffer_newevents(evtype=None, timeout=3000, verbose=False):
"""
Wait for and return any new events recieved from the buffer between
calls to this function
timeout = maximum time to wait in milliseconds before returning
"""
global ftc, nEvents # use to store number events processed accross function calls
if not "nEvents" in globals(): # first time initialize to events up to now
start, nEvents = ftc.poll()
if verbose:
print "Waiting for event(s) " + str(evtypes) + " with timeout_ms " + str(timeout_ms)
start = time.time()
elapsed_ms = 0
events = []
while len(events) == 0 and elapsed_ms < timeout:
nSamples, curEvents = ftc.wait(-1, nEvents, timeout_ms - elapsed_ms)
if curEvents > nEvents:
events = ftc.getEvents([nEvents, curEvents - 1])
if not evttype is None:
events = filter(lambda x: x.type in evtype, events)
nEvents = curEvents # update starting number events (allow for buffer restarts)
elapsed_ms = (time.time() - start) * 1000
return events
开发者ID:Quixotte,项目名称:bci_practical_heyni_boorn_janssen,代码行数:26,代码来源:bufhelp.py
示例3: why_opinion
def why_opinion(self):
feature_names = self.vectorizer.get_feature_names()
opinion_idx = list(np.argsort(self.clf.feature_log_prob_[1])) #most important are last
opinion_idx.reverse() #most important are first
self.opinion_idx = opinion_idx
i_filtered=0
i_opinion_idx = 0
filtered_keywords = []
stime=time.time()
while i_filtered<100:
if not self.vectorizer.get_feature_names()[opinion_idx[i_opinion_idx]] in nltk.corpus.stopwords.words('english'):
filtered_keywords.append(self.vectorizer.get_feature_names()[opinion_idx[i_opinion_idx]])
i_filtered+=1
i_opinion_idx+=1
self.fk=filtered_keywords
print 'why while: '+str(time.time()-stime)
news_words=[]
opinion_words = []
ratio = self.clf.feature_log_prob_[1]-self.clf.feature_log_prob_[0]
for i,count in enumerate(self.vect.toarray()[0]):
if count>0:
opinion_words.append([count*np.exp(ratio[i]), count, ratio[i], self.vectorizer.get_feature_names()[i]])
opinion_words_sorted = sorted(opinion_words, key=lambda x:x[2])
return opinion_words_sorted #, news_words_sorted
开发者ID:johnjoo1,项目名称:hype_control,代码行数:25,代码来源:mnb_live.py
示例4: testLargeDirReinstall
def testLargeDirReinstall(self):
"""Benchmark and test reinstalling FSD with a directory holding a large number of people"""
from time import time
from random import choice
qi = getToolByName(self.portal, 'portal_quickinstaller')
acl = getToolByName(self.portal, 'acl_users')
# pick a user and make sure they exist in acl_users before we start
user_id = choice(self.person_ids)
person = self.directory[user_id]
self.failUnless(acl.getUserById(id=user_id),"Problem: person is not listed in acl_users")
self.failUnless(person.UID(),"Problem: expected person object %s to have a UID. It does not" % person)
# how long does it take to reinstall FSD?
import time
start_time = time.time()
qi.reinstallProducts(products='FacultyStaffDirectory')
end_time = time.time()
elapsed_time = end_time-start_time
reinstall_report = "\nreinstalling FSD with a directory containing %s people took %s seconds\n" % (self.numPeople, elapsed_time)
print "\n" + ("*" * 20) + reinstall_report + ("*" * 20)
# test that a person in the FSD is still a user
self.failUnless(acl.getUserById(id=user_id),"Problem: after reinstall person is not listed in acl_users")
self.failUnless(person.UID(),"Problem: after reinstall expected person object %s to have a UID. It does not" % person)
开发者ID:alexmerser,项目名称:Products.FacultyStaffDirectory,代码行数:26,代码来源:testInstall.py
示例5: InsertKeyWordToDB
def InsertKeyWordToDB(fromSubDir,toSubDir):
db = DB()
parser = Parser()
for index in range(fromSubDir,toSubDir):
for root,dirs,files in os.walk('test/keyword/'+str(index)+"/"):
#each subdir: 1000record
start = time.time()
for afile in files:
if afile == '.DS_Store':
continue
words = afile.split('_')
aExpert = Expert(words[0].strip(),words[1].strip(),words[2].replace(".html","").strip())
aExpert.setKeyword(parser.parseKeyword(root,afile))
aExpert.ChangeKeywordsToString()
#print aExpert.keywordsList
if not db.isExpertExist(aExpert):
db.insertExpert(aExpert)
end = time.time()
db.conn.commit()
print ("KeywordSubDir %d is Done!"%index),
print time.strftime('%m-%d %H:%M:%S',time.localtime(time.time())),"total:",end-start
f = open("KeywordsToDB.log","a")
f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))+" keywordSubDir"+str(index)+" is Done! "+"total"+str(end-start) )
f.close()
db.close()
开发者ID:CharlesZhong,项目名称:CnkiProject,代码行数:30,代码来源:CnkiParser.py
示例6: InsertPaperToDB
def InsertPaperToDB(fromSubDir,toSubDir):
db = DB()
parser = Parser()
for index in range(fromSubDir,toSubDir):
for root,dirs,files in os.walk('test/paper/'+str(index)+"/"):
n = 1000*index
start = time.time()
for afile in files:
if afile == '.DS_Store':
continue
words = afile.split('_')
papers = (parser.parsePaper(root,afile))
for eachPapaer in papers:
if not db.isPaperExist(eachPapaer):
db.insertPaper(eachPapaer)
print "n:",n,
print "Expert_ID %s is done"%words[0]
n = n + 1
db.conn.commit()
end = time.time()
print ("PaperSubDir %d is Done!"%index),
print time.strftime('%m-%d %H:%M:%S',time.localtime(time.time())),"time:",end-start,
f = open("PaperToDB.log","a")
f.write(time.strftime('%m-%d %H:%M:%S',time.localtime(time.time()))+" paperSubDir"+str(index)+" is Done! "+"total"+str(end-start) )
f.close()
db.close()
开发者ID:CharlesZhong,项目名称:CnkiProject,代码行数:29,代码来源:CnkiParser.py
示例7: wait_for_server_status
def wait_for_server_status(self, server_id, desired_status, interval_time=None, timeout=None):
interval_time = int(interval_time or self.servers_api_config.server_status_interval)
timeout = int(timeout or self.servers_api_config.server_build_timeout)
end_time = time.time() + timeout
time.sleep(interval_time)
while time.time() < end_time:
resp = self.nova_cli_client.show_server(server_id)
server = resp.entity
if server.status.lower() == ServerStates.ERROR.lower():
raise BuildErrorException('Build failed. Server with uuid "{0} entered ERROR status.'.format(server.id))
if server.status == desired_status:
break
time.sleep(interval_time)
else:
raise TimeoutException(
"wait_for_server_status ran for {0} seconds and did not "
"observe server {1} reach the {2} status.".format(timeout, server_id, desired_status)
)
return resp
开发者ID:jc7998,项目名称:cloudcafe,代码行数:25,代码来源:behaviors.py
示例8: env454run_info_upload
def env454run_info_upload(runobj):
my_read_csv = dbUpload(runobj)
start = time.time()
my_read_csv.put_run_info()
elapsed = (time.time() - start)
print "put_run_info time = %s" % str(elapsed)
开发者ID:msGenDev,项目名称:py_mbl_sequencing_pipeline,代码行数:7,代码来源:pipelineprocessor.py
示例9: loadIntents
def loadIntents(node_id, urllist, intPerGroup, addrate, duration):
urlindex = 0
group = 0
start_id = 0
sleeptimer = (1.000/addrate)
tstart = time.time()
while ( (time.time() - tstart) <= duration ):
if urlindex < len(urllist):
realurlind = urlindex
else:
realurlind = 0
urlindex = 0
u = str(urllist[realurlind])
gstart = time.time()
intents,start_id = setIntentJSN(node_id, intPerGroup, group, start_id)
#print (str(intents))
#print ("Starting intent id: " + str(start_id))
result = post_json(u, intents)
#print json.dumps(intents[group])
#print ("post result: " + str(result))
gelapse = time.time() - gstart
print ("Group: " + str(group) + " with " + str(intPerGroup) + " intents were added in " + str('%.3f' %gelapse) + " seconds.")
sleep(sleeptimer)
urlindex += 1
group += 1
telapse = time.time() - tstart
#print ( "Number of groups: " + str(group) + "; Totoal " + str(args.groups * args.intPerGroup) + " intents were added in " + str(telapse) + " seconds.")
return telapse, group
开发者ID:Santhosh2488,项目名称:ONLabTest,代码行数:30,代码来源:loadgen_NB.py
示例10: waitnewevents
def waitnewevents(evtypes, timeout_ms=1000, verbose=True):
"""Function that blocks until a certain type of event is recieved.
evttypes is a list of event type strings, recieving any of these event types termintes the block.
All such matching events are returned
"""
global ftc, nEvents, nSamples, procnEvents
start = time.time()
update()
elapsed_ms = 0
if verbose:
print "Waiting for event(s) " + str(evtypes) + " with timeout_ms " + str(timeout_ms)
evt = None
while elapsed_ms < timeout_ms and evt is None:
nSamples, nEvents2 = ftc.wait(-1, procnEvents, timeout_ms - elapsed_ms)
if nEvents2 > nEvents: # new events to process
procnEvents = nEvents2
evts = ftc.getEvents((nEvents, nEvents2 - 1))
evts = filter(lambda x: x.type in evtype, evts)
if len(evts) > 0:
evt = evts
elapsed_ms = (time.time() - start) * 1000
nEvents = nEvents2
return evt
开发者ID:Quixotte,项目名称:bci_practical_heyni_boorn_janssen,代码行数:27,代码来源:bufhelp.py
示例11: ana_file_sync
def ana_file_sync(self,pflag):
g.tprinter('Running ana_file_sync',pflag)
self.missing_data_list = np.array(['missing'])
tbaf = 0
for i in self.data_list:
tstart = time.time()
if i in self.ana_file: ##Overvej om det virkelig er det kvikkeste!
#g.printer('is in file',pflag)
pass
else:
#g.printer('is not in file',pflag)
self.missing_data_list = np.append(self.missing_data_list,i)
print time.time()-tstart
if tbaf == 0:
g.printer('ana_file is up to date',pflag)
else:
g.printer(str(tbaf)+' files have to be added to ana_file',pflag)
for i in self.missing_data_list[1:]:
k = os.path.split(i)
info = k[-1].split('.')[-2].split('_')
num_of_zeros = len(self.ana_file[0])-len(info)-1
info = np.append(info,np.zeros(num_of_zeros))
info = np.append(info,np.array(i))
self.ana_file = np.vstack((self.ana_file,info))
开发者ID:OliStein,项目名称:Frascati_2014_readout,代码行数:35,代码来源:analysis_modules.py
示例12: DetectSound
def DetectSound():
# Get data from landmark detection (assuming face detection has been activated).
data = memoryProxy.getData("SoundDetected")
##The SoundDetected key is organized as follows:
##
##[[index_1, type_1, confidence_1, time_1],
## ...,
##[index_n, type_n, confidence_n, time_n]]
##
##n is the number of sounds detected in the last audio buffer,
##index is the index (in samples) of either the sound start (if type is equal to 1) or the sound end (if type is equal to 0),
##time is the detection time in micro seconds
##confidence gives an estimate of the probability [0;1] that the sound detected by the module corresponds to a real sound.
if len(data)==0:
detected=False
timestamp=time.time()
soundInfo=[]
else:
detected=True
timestamp=time.time()
soundInfo=[]
for snd in data:
soundInfo.append([ snd[0], #index of sound start/end
snd[1], #type: 1=start, 0=end
snd[2] #confidence: probability that there was a sound
])
return detected, timestamp, soundInfo
开发者ID:Rctue,项目名称:nao-lib,代码行数:29,代码来源:nao_nocv_1_2.py
示例13: _log_rate
def _log_rate(output_f,d, message=None):
"""Log a message for the Nth time the method is called.
d is the object returned from init_log_rate
"""
import time
if d[2] <= 0:
if message is None:
message = d[4]
# Average the rate over the length of the deque.
d[6].append(int( d[3]/(time.time()-d[1])))
rate = sum(d[6])/len(d[6])
# Prints the processing rate in 1,000 records per sec.
output_f(message+': '+str(rate)+'/s '+str(d[0]/1000)+"K ")
d[1] = time.time()
# If the print_rate was specified, adjuect the number of records to
# aaproximate that rate.
if d[5]:
target_rate = rate * d[5]
d[3] = int((target_rate + d[3]) / 2)
d[2] = d[3]
d[0] += 1
d[2] -= 1
开发者ID:kball,项目名称:ambry,代码行数:33,代码来源:__init__.py
示例14: wait_ms
def wait_ms(prev_time_ms, wait_time_ms):
t = time.time()*1000. - prev_time_ms
while t < wait_time_ms:
if t < 0:
break
sleep((wait_time_ms - t)/1000.)
t = time.time()*1000. - prev_time_ms
开发者ID:chanokin,项目名称:pyDVS,代码行数:7,代码来源:mnist_to_spikes.py
示例15: alligator
def alligator():
import time
start_time = time.time()
product_sum = 0
check_pandigital = False
set_of_products = set()
def pandigital(l):
seen = set() # Start with an empty set
for i in l:
if i in seen:
return False
seen.add(i) # If it is not in the seen set, then add it.
return True
for x in range(1, 2000):
for y in range(x+1, 2000):
z = x * y
digits = str(x) + str(y) + str(z) # This takes all three numbers and joins them into one long number
if (len(digits) == 9 and "0" not in (digits) and pandigital(digits)):
if z not in set_of_products:
set_of_products.add(z)
product_sum = product_sum + z
print ("The sum of the pandigital products is: ", product_sum)
print("--- %s seconds ---" % (time.time() - start_time))
开发者ID:mbh038,项目名称:PE,代码行数:28,代码来源:PE_0032.py
示例16: do_real_import
def do_real_import(self, vsfile, filepath,mdXML,import_tags):
"""
Make the import call to vidispine, and wait for self._importer_timeout seconds for the job to complete.
Raises a VSException representing the job error if the import job fails, or ImportStalled if the timeout occurs
:param vsfile: VSFile object to import
:param filepath: filepath of the VSFile
:param mdXML: compiled metadata XML to import alongside the media
:param import_tags: shape tags describing required transcodes
:return: None
"""
import_job = vsfile.importToItem(mdXML, tags=import_tags, priority="LOW", jobMetadata={"gnm_app": "vsingester"})
job_start_time = time.time()
close_sent = False
while import_job.finished() is False:
self.logger.info("\tJob status is %s" % import_job.status())
if time.time() - job_start_time > self._importer_timeout:
self.logger.error("\tJob has taken more than {0} seconds to complete, concluding that it must be stalled.".format(self._importer_timeout))
import_job.abort()
self.logger.error("\tSent abort signal to job")
raise ImportStalled(filepath)
if time.time() - job_start_time > self._close_file_timeout and not close_sent:
vsfile.setState("CLOSED")
sleep(5)
import_job.update(noraise=False)
开发者ID:guardian,项目名称:assetsweeper,代码行数:25,代码来源:importer_thread.py
示例17: test_vrr
def test_vrr():
import time
xa,ya,za = 0.,0.,0.
xb,yb,zb = 0.,0.,0.
xc,yc,zc = 0.,0.,0.
xd,yd,zd = 0.,0.,0.
norma = normb = normc = normd = 1.
alphaa = alphab = alphac = alphad = 1.
la,ma,na = 0,0,0
lc,mc,nc = 0,0,0
M = 0
t0 = time.time()
val1 = vrr((xa,ya,za),norma,(la,ma,na),alphaa,
(xb,yb,zb),normb,alphab,
(xc,yc,zc),normc,(lc,mc,nc),alphac,
(xd,yd,zd),normd,alphad,M)
t1 = time.time()
val2 = vrr((xc,yc,zc),normc,(lc,mc,nc),alphac,
(xd,yd,zd),normd,alphad,
(xa,ya,za),norma,(la,ma,na),alphaa,
(xb,yb,zb),normb,alphab,M)
t2 = time.time()
print "Values: ",val1,val2
print "Timings: ",t1-t0,t2-t1
return
开发者ID:certik,项目名称:pyquante,代码行数:27,代码来源:hgp.py
示例18: crawl
def crawl(self):
_starttime = time.time()
if self.restrict == None:
self.restrict = "http://%s.*" % self.init_domain
print "Deadlink-crawler version 1.1"
print "Starting crawl from URL %s at %s with restriction %s\n" % (self.init_url, strftime("%Y-%m-%d %H:%M:%S", gmtime()), "http://%s.*" % self.init_domain)
while len(self.frontier) > 0:
time.sleep(self.wait_time)
next_time, next_url = self.frontier.next()
while time.time() < next_time:
time.sleep(0.5)
try:
self.visit_url(next_url[0], next_url[1])
except urllib2.URLError:
continue
self.print_deadlinks(self.deadlinks)
_elapsed = time.time() - _starttime
print "\nSummary:\n--------"
print "Crawled %d pages and checked %d links in %s time." % (self._pages, self._links, strftime("%H:%M:%S", gmtime(_elapsed)))
print "Found a total of %d deadlinks in %d different pages" % (self._dead, self._via)
if len(self.deadlinks) == 0:
exit(0)
else:
exit(2)
开发者ID:janhoy,项目名称:deadlink-crawler,代码行数:33,代码来源:crawler.py
示例19: treat_movement
def treat_movement(self, rp, movement):
if movement["status"] in ["error", "done"]:
return
now = int(time.time())
movement["begin"] = now
movement["status"] = "treating"
self.memory.update_movement(movement)
# checking sources
movement["src_exist"] = True
if not os.path.exists(rp["src"]):
now = int(time.time())
movement["src_exist"] = False
movement["status"] = "error"
movement["end"] = now
movement["error"] = "source file : %s does not exist" % (rp["src"])
self.memory.update_movement(movement)
return
# adapt in function of protocol
if movement["protocol"] == "cp":
self.do_cp(movement, rp)
return
if movement["protocol"] == "ftp":
self.do_ftp(movement, rp)
return
now = int(time.time())
movement["status"] = "error"
movement["end"] = now
movement["error"] = "protocol %s not known" % (movement["protocol"])
self.memory.update_movement(movement)
rp["status"] = "done"
self.memory.update_relative_path(rp)
开发者ID:bearstech,项目名称:bokor,代码行数:34,代码来源:post.py
示例20: timer
def timer(self, object, cdata=''):
if object:
t = time.time()
r = self.render(object, cdata)
self.tagTimes[object.__class__.__name__] = time.time() - t
return r
return self.render(object, cdata)
开发者ID:MounikaArkala,项目名称:txstateprojects,代码行数:7,代码来源:parser.py
注:本文中的time.time.time函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论