def train_model(self, max_iters):
"""Network training loop."""
last_snapshot_iter = -1
timer = Timer()
while self.solver.iter < max_iters:
timer.tic()
self.solver.step(1)
print 'fc9_1:',sorted(self.solver.net.params['fc9_1'][0].data[0])[-1]
#print 'fc9:',sorted(self.solver.net.params['fc9'][0].data[0])[-1]
#print 'fc7:',sorted(self.solver.net.params['fc7'][0].data[0])[-1]
#print 'fc6:',sorted(self.solver.net.params['fc6'][0].data[0])[-1]
#print 'fc9:',(self.solver.net.params['fc9'][0].data[0])[0]
#print 'fc7:',(self.solver.net.params['fc7'][0].data[0])[0]
#print 'fc6:',(self.solver.net.params['fc6'][0].data[0])[0]
#print 'conv5_3:',self.solver.net.params['conv5_3'][0].data[0][0][0]
#print 'conv5_2:',self.solver.net.params['conv5_2'][0].data[0][0][0]
#print 'conv5_1:',self.solver.net.params['conv5_1'][0].data[0][0][0]
#print 'conv4_3:',self.solver.net.params['conv4_3'][0].data[0][0][0]
#print 'fc9:',self.solver.net.params['fc9'][0].data[0][0]
timer.toc()
if self.solver.iter % (10 * self.solver_param.display) == 0:
print 'speed: {:.3f}s / iter'.format(timer.average_time)
python类Timer()的实例源码
def removeEntry(self, entry):
print "[Timer] Remove " + str(entry)
# avoid re-enqueuing
entry.repeated = False
# abort timer.
# this sets the end time to current time, so timer will be stopped.
entry.autoincrease = False
entry.abort()
if entry.state != entry.StateEnded:
self.timeChanged(entry)
# print "state: ", entry.state
# print "in processed: ", entry in self.processed_timers
# print "in running: ", entry in self.timer_list
# autoincrease instanttimer if possible
if not entry.dontSave:
for x in self.timer_list:
if x.setAutoincreaseEnd():
self.timeChanged(x)
# now the timer should be in the processed_timers list. remove it from there.
self.processed_timers.remove(entry)
self.saveTimer()
def timer(self, *t_args, **t_kwargs):
"""Method that returns a decorator to automatically set up a timer and associate it with a function to run at the specified time
Code in this function gets executed immediately, not when the associated function runs.
It dynamically accepts arguments and passes them off to a 'Timer' class instance
"""
def decorator(timer_function):
"""This takes the timer's associated function as the only argument
It defines the decorator and wrapper, as well as setting up the 'Timer' object and associating it with the decorated function.
"""
if 'name' not in t_kwargs: # No name for this timer was provided; use function name
t_kwargs['name'] = timer_function.__name__
# Create an instance of the 'Timer' class
new_timer = Timer(self.scheduler, *t_args, **t_kwargs) # provide a reffrence to the scheduler and all wrapper arguments to this instance
def wrapper(*args, **kwargs):
"""This function is what will be called in place of the decorated function;
It takes the arguments given to it and passes them on to the provided function.
"""
r = timer_function(*args, **kwargs) # call the original trigger function
return r
new_timer.add_function(wrapper) # Associate the wrapper with the timer object
# add the timer to an internal list
self.timers.append(new_timer)
return wrapper
return decorator
def try_server_call(partial_function):
"""
Simple server call wrapper function.
- Take a functools.partial object with the function to call and arguments populated.
- Calls the method, and logs how long the server takes to respond.
"""
with Timer() as t:
try:
results = partial_function()
except Exception, err:
logger.critical(
"User '%s' (id: %s) failed to get response from server.",
name, name_to_id(name))
logger.critical("Function call: %s(%s)",
str(partial_function.func).split()[2], None)
logger.critical("Error: %s", repr(err))
raise # Debug
# return None
logger.debug("%.03f - %s (results: %s)",
t.elapsed, str(partial_function.func).split()[2], results)
return results
def forwardDist(self, speed, distTarget, stop = True, decel = False):
phi0 = self.odometer.getPhi()
x0, y0 = self.odometer.getPosXY()
dist = 0
loopTimer = Timer()
if decel:
while dist < distTarget - speed * 3 * self.timeStep:
self.forwardAngle(speed, phi0)
loopTimer.sleepToElapsed(self.timeStep)
x1, y1 = self.odometer.getPosXY()
dist = sqrt((x1 - x0)**2 + (y1 - y0)**2)
if distTarget - dist < 50 and speed > 75:
speed = speed / 1.3
else:
while dist < distTarget:
self.forwardAngle(speed, phi0)
loopTimer.sleepToElapsed(self.timeStep)
x1, y1 = self.odometer.getPosXY()
dist = sqrt((x1 - x0)**2 + (y1 - y0)**2)
if stop:
self.stop()
# In-loop; Need to call this method within a loop with a short time step
# in order for the PID to adjust the turn rate (targetOmega).
def turnToAngle(self, angleTarget, omega = pi):
self.setMode('TURN')
self.targetV = 0
self.targetOmega = 0
omegaMin = pi / 8.
angleTol = pi/180.
loopTimer = Timer()
while abs(self.odometer.angleRelToPhi(angleTarget)) > angleTol:
angle = self.odometer.angleRelToPhi(angleTarget)
if angle > pi / 6:
self.targetOmega = omega
elif angle > 0:
self.targetOmega = omegaMin
elif angle < -pi / 6:
self.targetOmega = -omega
else:
self.targetOmega = -omegaMin
loopTimer.sleepToElapsed(self.timeStep)
self.stop()
########################################################################
## Other methods
########################################################################
# Kill thread running ._move() method
def remove(self, entry):
print("[EPGRefresh] Timer removed " + str(entry))
# avoid re-enqueuing
entry.repeated = False
# abort timer.
# this sets the end time to current time, so timer will be stopped.
entry.abort()
if entry.state != entry.StateEnded:
self.timeChanged(entry)
print("state: ", entry.state)
print("in processed: ", entry in self.processed_timers)
print("in running: ", entry in self.timer_list)
# now the timer should be in the processed_timers list. remove it from there.
self.processed_timers.remove(entry)
def apply_refraction(self, us_time):
"""Implements a refractory period for each pixel.
Does not modify instance data
In other words, if an event occurs within 'us_time' microseconds of
a previous event at the same pixel, then the second event is removed
us_time: time in microseconds
"""
t0 = np.ones((self.width, self.height)) - us_time - 1
valid_indices = np.ones(len(self.data), np.bool_)
#with timer.Timer() as ref_timer:
i = 0
for datum in np.nditer(self.data):
datum_ts = datum['ts'].item(0)
datum_x = datum['x'].item(0)
datum_y = datum['y'].item(0)
if datum_ts - t0[datum_x, datum_y] < us_time:
valid_indices[i] = 0
else:
t0[datum_x, datum_y] = datum_ts
i += 1
#print 'Refraction took %s seconds' % ref_timer.secs
return self.data[valid_indices.astype('bool')]
def main():
logger = init_logger("main")
logger.info("start program")
p = ProgramArguments()
try:
p.parse()
except ArgPathToFileError:
exit(2)
logger.info(p.path_to_file + p.function_name + p.module_name
+ str(p.timeout) + p.init_struct_code + p.step + str(p.repeat))
timer = Timer(p.path_to_file, p.function_name, p.module_name, p.timeout,
p.init_struct_code, p.step, p.repeat)
try:
time_list = timer.measure_time()
except ArgFunNameError:
print("There is no such a fucntion :" + p.function_name)
exit(2)
try:
estimate_complexity(time_list)
except NotEnoughStepsError:
exit(2)
logger.info("end program")
def __init__(self):
timer.Timer.__init__(self)
self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "pm_timers.xml")
try:
self.loadTimer()
except IOError:
print "unable to load timers from file!"
def loadTimer(self):
# TODO: PATH!
if not Directories.fileExists(self.Filename):
return
try:
file = open(self.Filename, 'r')
doc = xml.etree.cElementTree.parse(file)
file.close()
except SyntaxError:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("The timer file (pm_timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
print "pm_timers.xml failed to load!"
try:
import os
os.rename(self.Filename, self.Filename + "_old")
except (IOError, OSError):
print "renaming broken timer failed"
return
except IOError:
print "pm_timers.xml not found!"
return
root = doc.getroot()
# put out a message when at least one timer overlaps
checkit = True
for timer in root.findall("timer"):
newTimer = createTimer(timer)
if (self.record(newTimer, True, dosave=False) is not None) and (checkit == True):
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("Timer overlap in pm_timers.xml detected!\nPlease recheck it!"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
checkit = False # at moment it is enough when the message is displayed one time
def record(self, entry, ignoreTSC=False, dosave=True): #wird von loadTimer mit dosave=False aufgerufen
entry.timeChanged()
print "[PowerTimer]",str(entry)
entry.Timer = self
self.addTimerEntry(entry)
if dosave:
self.saveTimer()
return None
def __init__(self):
timer.Timer.__init__(self)
self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
try:
self.loadTimer()
except IOError:
print "unable to load timers from file!"
def loadTimer(self):
if not Directories.fileExists(self.Filename):
return
try:
file = open(self.Filename, 'r')
doc = xml.etree.cElementTree.parse(file)
file.close()
except SyntaxError:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
print "timers.xml failed to load!"
try:
os.rename(self.Filename, self.Filename + "_old")
except (IOError, OSError):
print "renaming broken timer failed"
return
except IOError:
print "timers.xml not found!"
return
root = doc.getroot()
checkit = False
timer_text = ""
for timer in root.findall("timer"):
newTimer = createTimer(timer)
conflict_list = self.record(newTimer, ignoreTSC=True, dosave=False, loadtimer=True)
if conflict_list:
checkit = True
if newTimer in conflict_list:
timer_text += _("\nTimer '%s' disabled!") % newTimer.name
if checkit:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!") + timer_text, type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
timeitContext.py 文件源码
项目:Learning-Concurrency-in-Python
作者: PacktPublishing
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def myFunction():
# We create this context so that we can crawl
# https sites
myssl = ssl.create_default_context();
myssl.check_hostname=False
myssl.verify_mode=ssl.CERT_NONE
with Timer() as t:
req = Request('https://tutorialedge.net', headers={'User-Agent': 'Mozilla/5.0'})
response = urlopen(req, context=myssl)
print("Elapsed Time: {} seconds".format(t.elapsed))
def __init__(self):
timer.Timer.__init__(self)
self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
try:
self.loadTimer()
except IOError:
print "unable to load timers from file!"
def loadTimer(self):
if not Directories.fileExists(self.Filename):
return
try:
doc = xml.etree.cElementTree.parse(self.Filename)
except SyntaxError:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
print "timers.xml failed to load!"
try:
import os
os.rename(self.Filename, self.Filename + "_old")
except (IOError, OSError):
print "renaming broken timer failed"
return
except IOError:
print "timers.xml not found!"
return
root = doc.getroot()
checkit = False
timer_text = ""
for timer in root.findall("timer"):
newTimer = createTimer(timer)
conflict_list = self.record(newTimer, ignoreTSC=True, dosave=False, loadtimer=True)
if conflict_list:
checkit = True
if newTimer in conflict_list:
timer_text += _("\nTimer '%s' disabled!") % newTimer.name
if checkit:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!") + timer_text, type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
def record(self, entry, ignoreTSC=False, dosave=True, loadtimer=False):
check_timer_list = self.timer_list[:]
timersanitycheck = TimerSanityCheck(check_timer_list,entry)
answer = None
if not timersanitycheck.check():
if not ignoreTSC:
print "[RecordTimer] timer conflict detected!"
print timersanitycheck.getSimulTimerList()
return timersanitycheck.getSimulTimerList()
else:
print "[RecordTimer] ignore timer conflict..."
if not dosave and loadtimer:
simulTimerList = timersanitycheck.getSimulTimerList()
if entry in simulTimerList:
entry.disabled = True
if entry in check_timer_list:
check_timer_list.remove(entry)
answer = simulTimerList
elif timersanitycheck.doubleCheck():
print "[RecordTimer] ignore double timer..."
return None
entry.timeChanged()
print "[Timer] Record " + str(entry)
entry.Timer = self
self.addTimerEntry(entry)
if dosave:
self.saveTimer()
return answer
def removeEntry(self, entry):
print "[Timer] Remove " + str(entry)
# avoid re-enqueuing
entry.repeated = False
# abort timer.
# this sets the end time to current time, so timer will be stopped.
entry.autoincrease = False
entry.abort()
if entry.state != entry.StateEnded:
self.timeChanged(entry)
print "state: ", entry.state
print "in processed: ", entry in self.processed_timers
print "in running: ", entry in self.timer_list
# autoincrease instanttimer if possible
if not entry.dontSave:
for x in self.timer_list:
if x.setAutoincreaseEnd():
self.timeChanged(x)
if entry in self.processed_timers:
# now the timer should be in the processed_timers list. remove it from there.
self.processed_timers.remove(entry)
self.saveTimer()
def __init__(self):
timer.Timer.__init__(self)
self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "pm_timers.xml")
try:
self.loadTimer()
except IOError:
print "unable to load timers from file!"
def loadTimer(self):
# TODO: PATH!
if not Directories.fileExists(self.Filename):
return
try:
file = open(self.Filename, 'r')
doc = xml.etree.cElementTree.parse(file)
file.close()
except SyntaxError:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("The timer file (pm_timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
print "pm_timers.xml failed to load!"
try:
import os
os.rename(self.Filename, self.Filename + "_old")
except (IOError, OSError):
print "renaming broken timer failed"
return
except IOError:
print "pm_timers.xml not found!"
return
root = doc.getroot()
# put out a message when at least one timer overlaps
checkit = True
for timer in root.findall("timer"):
newTimer = createTimer(timer)
if (self.record(newTimer, True, dosave=False) is not None) and (checkit == True):
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("Timer overlap in pm_timers.xml detected!\nPlease recheck it!"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
checkit = False # at moment it is enough when the message is displayed one time
def record(self, entry, ignoreTSC=False, dosave=True): #wird von loadTimer mit dosave=False aufgerufen
entry.timeChanged()
print "[PowerTimer]",str(entry)
entry.Timer = self
self.addTimerEntry(entry)
if dosave:
self.saveTimer()
return None
def __init__(self):
timer.Timer.__init__(self)
self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml")
try:
self.loadTimer()
except IOError:
print "[RecordTimer] unable to load timers from file!"
def loadTimer(self):
try:
file = open(self.Filename, 'r')
doc = xml.etree.cElementTree.parse(file)
file.close()
except SyntaxError:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
print "[RecordTimer] timers.xml failed to load!"
try:
os.rename(self.Filename, self.Filename + "_old")
except (IOError, OSError):
print "[RecordTimer] renaming broken timer failed"
return
except IOError:
print "[RecordTimer] timers.xml not found!"
return
root = doc.getroot()
# put out a message when at least one timer overlaps
checkit = False
timer_text = ""
for timer in root.findall("timer"):
newTimer = createTimer(timer)
conflict_list = self.record(newTimer, ignoreTSC=True, dosave=False, loadtimer=True)
if conflict_list:
checkit = True
if newTimer in conflict_list:
timer_text += _("\nTimer '%s' disabled!") % newTimer.name
if checkit:
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!") + timer_text, type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed")
def goToPoint(point, speed):
lt = Timer()
angle, dist = angleDistToPoint(point)
#print angle, dist
rpb202.motionCtrl.turnToAngle(angle)
while dist > 100:
rpb202.motionCtrl.forwardAngle(speed, angle)
lt.sleepToElapsed(.02)
angle, dist = angleDistToPoint(point)
rpb202.motionCtrl.forwardDist(speed, dist, decel=True)
rpb202.stop()
print rpb202.odometer.getPosXY()
def _run(self):
try:
loopTimer = Timer()
while self.active:
speedL = self.targetV - self.targetOmega * self.odometer.track / 2.
speedR = self.targetV + self.targetOmega * self.odometer.track / 2.
self.motors.speed(speedL, speedR)
loopTimer.sleepToElapsed(self.timeStep)
self.odometer.update()
except IOError:
print "IOError - Stopping"
self.stop()
self.kill()
# Starts the ._run() method in a thread
def register_timer_handler(self,internal,func,delay=0):
'''
??????internal ?????timer
'''
import timer,time
tme=timer.Timer(time.time()+delay,internal,func)
self._loop.add_timer(tme)
return tme.timer_id
def add_timer_task(self, internal, func, delay=0):
'''
???????
'''
import timer, time
tme = timer.Timer(time.time() + delay, internal, func)
self.loop.add_timer(tme)
return tme.timer_id
def add_timer_task(self,internal,func,delay=0):
'''
???????
'''
import timer, time
tme = timer.Timer(time.time()+delay, internal, func)
self.loop.add_timer(tme)
return tme.timer_id
def myFunction():
# We create this context so that we can crawl
# https sites
myssl = ssl.create_default_context();
myssl.check_hostname=False
myssl.verify_mode=ssl.CERT_NONE
with Timer() as t:
req = Request('https://tutorialedge.net', headers={'User-Agent': 'Mozilla/5.0'})
response = urlopen(req, context=myssl)
print("Elapsed Time: {} seconds".format(t.elapsed))