本文整理汇总了Python中utils.Timer类的典型用法代码示例。如果您正苦于以下问题:Python Timer类的具体用法?Python Timer怎么用?Python Timer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Timer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ToggleAnimation
class ToggleAnimation(AnimationActionSprite, Triggered):
"Animation that can be toggled on/off. """
def __init__(self, **others):
Triggered.__init__(self, **others)
AnimationActionSprite.__init__(self, **others)
self.debugging = False
self.playing = False
self.timer = Timer(0.2)
self.animation_player.backwards = True
def update(self, player, collisions_group, **others):
self.dprint("\n### ToggleAnimation.update()")
e = self.get_trigger(self.triggered_code)
self.dprint("\tEvent:" + str(e))
if self.timer.finished and e:
self.timer.reset()
self.dprint("\t\tToggling Animation")
if self.playing:
self.dprint("\t\t\tDeactivating animation")
self.playing = False
else:
self.dprint("\t\t\tActivating animation")
self.playing = True
if self.playing:
self.next_frame()
示例2: _find_seeks_index
def _find_seeks_index(dbfile, indexname, queries, debug=False):
"""Use the index file to find exact seek positions for relevant
records. End locations are not necessary since we are guaranteed that
the data will be present, so a number of occurances is sufficient for
prompt termination."""
timer = Timer(rl_min_dur=1)
locs = Counter()
if debug:
print " Searching index..."
indexfh = ChunkedFile(dbfile, indexname, mode='r')
last_bookmark = 0
for query in sorted(queries):
# Use bookmarks to rapidly search the index!
bookmark = indexfh.find_bookmark(query.encode('utf-8'))
if bookmark != last_bookmark:
indexfh.seek(bookmark)
#print " Seek to", bookmark
last_bookmark = bookmark
for i, line in enumerate(indexfh):
title, nums = line.decode('utf-8').split('\t')
if i % 100 == 0:
timer.step()
if title in queries:
locs.update(int(x) for x in nums.split(' '))
elif title > query:
break # This works because the index is sorted.
indexfh.close()
for start, nresults in sorted(locs.items()):
yield (start, None, nresults)
if debug:
print ' Completed in', timer, 'seconds.'
示例3: RemoteSubscriber
class RemoteSubscriber(object):
def __init__(self, uuid, commandID, ipaddress="", port=32400, protocol="http", name=""):
self.poller = False
self.uuid = uuid
self.commandID = commandID
self.url = ""
self.name = name
self.lastUpdated = Timer()
if ipaddress and protocol:
self.url = "%s://%s:%s" % (protocol, ipaddress, port)
def refresh(self, sub):
log.debug("RemoteSubscriber::refresh %s (cid=%s)" % (self.uuid, sub.commandID))
if sub.url != self.url:
log.debug("RemoteSubscriber::refresh new url %s", sub.url)
self.url = sub.url
if sub.commandID != self.commandID:
log.debug("RemoteSubscriber::refresh new commandID %s", sub.commandID)
self.commandID = sub.commandID
self.lastUpdated.restart()
def shouldRemove(self):
if self.lastUpdated.elapsed() > SUBSCRIBER_REMOVE_INTERVAL:
log.debug("RemoteSubscriber::shouldRemove removing %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
return True
log.debug("RemoteSubscriber::shouldRemove will not remove %s because elapsed: %lld" % (self.uuid, self.lastUpdated.elapsed()))
return False
示例4: convert_model_data
def convert_model_data(subpath):
tm = Timer()
fullpath = os.path.join(baseDir, subpath)
objects = {}
mtllib = None
vertices = []
texcoords = [[0, 0]]
normals = []
mtlBaseDir = os.path.split(fullpath)[0]
lineID = 0
for line in open(fullpath, "r"):
lineID += 1
# print lineID
if line.startswith('#'): continue
v = line.split()
if not v: continue
if v[0] == 'o' or v[0] == 'g':
name = v[1].split('_')[0]
obj = _Object(name)
objects[obj.name] = obj
elif v[0] == 'usemtl':
materialName = v[1]
obj.material = mtllib.get(materialName)
elif v[0] == 'v':
assert len(v) == 4
v = map(float, v[1:4])
vertices.append(v)
elif v[0] == 'vn':
assert len(v) == 4
v = map(float, v[1:4])
normals.append(v)
elif v[0] == 'vt':
assert len(v) == 3
v = map(float, v[1:3])
texcoords.append(v)
elif v[0] == 'mtllib':
mtllib = MaterialLib.load(os.path.realpath(
os.path.join(mtlBaseDir, v[1])))
elif v[0] == 'f':
indices = v[1:]
assert len(indices) == 3, 'please use triangle faces'
# each index tuple: (v, t, n)
for x in indices:
x = x.split('/')
vi, ti, ni = map(int, x)
obj.vdata.extend(
texcoords[ti] + normals[ni-1] + vertices[vi-1])
data = {
'objects': objects,
'mtllib': mtllib,
}
print 'convert {}, time: {}ms'.format(subpath, tm.tick())
return data
示例5: __init__
class QueryExecutor:
index = None
timer = None
def __init__(self, index):
self.index = index
def executeQueries(self, queryList):
self.timer = Timer()
self.timer.start()
queryMatchingList = []
executedTokens = 0
for query in queryList:
searchTokens = query.getSearchTokens()
excludedTokens = query.getExcludedTokens()
searchResult = QueryResult()
for token in searchTokens:
executedTokens += 1
tmpPostingsList = self.index.getDictionary().getPostingsList(token)
searchResult.addPostingList(token, tmpPostingsList)
excludedResult = QueryResult()
for token in excludedTokens:
tmpPostingsList = self.index.getDictionary().getPostingsList(token)
excludedResult.addPostingList(token, tmpPostingsList)
if(len(excludedResult.getItems()) > 0):
queryMatching = QueryResult.mergeWithExclusions(searchResult, excludedResult)
else:
queryMatching = searchResult
queryMatchingList.append(queryMatching)
queryMatching = QueryResult.mergeWithIntersection(queryMatchingList)
rankedResult = RankedResult()
for doc, queryResultItem in queryMatching.getItems().items():
rank = RankProvider.provideRank(queryResultItem, executedTokens)
rankedResultItem = RankedResultItem(doc, rank, queryResultItem)
rankedResult.addRankedResultItem(rankedResultItem)
self.timer.stop()
return rankedResult.getSortedResult()
def getTimer(self):
return self.timer
示例6: load_models
def load_models():
tm = Timer()
if config.GZIP_LEVEL is not None:
infile = gzip.open(config.DAT_PATH, 'rb', config.GZIP_LEVEL)
else:
infile = open(config.DAT_PATH, 'rb')
# data = infile.read()
modeldatas = cPickle.loads(infile.read())
infile.close()
print 'load dat time: {}ms'.format(tm.tick())
for filepath, data in modeldatas.iteritems():
models[filepath] = load_single(filepath, data)
示例7: __init__
def __init__(self, screen, pos, images, scroll_period, duration=-1):
"""
If duration == -1, animation goes on indefinetly.
"""
self.screen = screen
self.pos = pos
self.images = [pygame.image.load(image) for image in images]
self.image_ptr = 0
self.scroll_period = scroll_period
self.duration = duration
self.active = True
self.scroll_timer = Timer(scroll_period, self.advance_images)
self.active_timer = Timer(duration, self.inactivate, 1)
示例8: __init__
def __init__(self):
self._player = None
self._video = None
self._lock = RLock()
self.last_update = Timer()
self.__part = 1
示例9: update_display
def update_display(self, elevators, floors):
# elevator positions
for i, e in enumerate(elevators):
self.print_elevator(i, e.old_pos, c=" " * (len(str(e)) + 2))
self.print_elevator(i, e.pos, c=str(e), color=e.state)
# rider counds
for f in xrange(len(floors)):
m = len(floors[f])
self.screen.print_at(" " * 20, self.frame_x + 2, self.frame_y + self.frame_h - 2 - f)
label = "{:<10}{:<3}({})".format("*" * min(m, 10), "..." if m > 10 else "", m)
self.screen.print_at(label, self.frame_x + 2, self.frame_y + self.frame_h - 2 - f)
# stats:
self.screen.print_at(" " * self.frame_w, self.frame_x, self.frame_y - 1)
self.screen.print_at(
"Time: {:<6.1f}, Produced: {:<6}, Delivered: {:<6} ({:<2.0f}%), Died: {:<6} ({:2.0f}%)".format(
Timer.timer(self.game).time(),
self.game.produced,
self.game.delivered,
100.0 * self.game.delivered / self.game.produced,
self.game.died,
100.0 * self.game.died / self.game.produced,
),
self.frame_x,
self.frame_y - 1,
)
self.screen.refresh()
示例10: __init__
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode( [self.SCREEN_WIDTH,self.SCREEN_HEIGHT],0,32 )
self.tile_img = pygame.image.load(self.BG_TITLE_IMG).convert_alpha()
self.tile_img_rect = self.tile_img.get_rect()
self.field_box = self.getFieldBox()
self.tboard = self.getTboard()
self.mboard = self.getMBoard()
self.clock = pygame.time.Clock()
self.creep_images = list()
self.paused = False
self.creep_images = [
( pygame.image.load(f1).convert_alpha(), pygame.image.load(f2).convert_alpha() )
for f1,f2 in self.CREEP_FILENAMES ]
explosion_img = pygame.image.load('images/explosion1.png').convert_alpha()
self.explosion_images = [ explosion_img, pygame.transform.rotate(explosion_img,90) ]
self.field_rect = self.getFieldRect()
self.creeps = pygame.sprite.Group()
self.spawnNewCreep()
self.creep_spawn_timer = Timer(500, self.spawnNewCreep)
self.createWalls()
# create the grid path representation of the grid
self.grid_nrows = self.FIELD_SIZE[1]/self.GRID_SIZE
self.grid_ncols = self.FIELD_SIZE[0]/self.GRID_SIZE
self.goal_coord = self.grid_nrows - 1, self.grid_ncols - 1
self.gridpath = GridPath(self.grid_nrows,self.grid_ncols,self.goal_coord)
for wall in self.walls:
self.gridpath.set_blocked(wall)
self.options = dict( draw_grid=False )
示例11: storeIndex
def storeIndex(self):
self.timer = Timer()
self.timer.start()
storage = Storage()
storage.saveIndex(self.dictionary)
self.timer.stop()
示例12: worker
def worker(args):
label, method = args
# call the requested method
try:
logger.info('%s: call to DataBuilder.%s' % (label, method))
t = Timer()
data = getattr(databuilder, method)()
t.stop()
logger.info('%s: done [%.1fs]' % (label, t.elapsed))
return label, data, None
except:
import StringIO
import traceback
buffer = StringIO.StringIO()
traceback.print_exc(file = buffer)
return label, None, buffer.getvalue()
示例13: __init__
def __init__(self, **others):
Triggered.__init__(self, **others)
OnceAnimationActionSprite.__init__(self, **others)
self.debugging = False
self.playing = False
self.timer = Timer(0.2)
self.debugging = False
示例14: __init__
def __init__(self, uuid, commandID, ipaddress="", port=32400, protocol="http", name=""):
self.poller = False
self.uuid = uuid
self.commandID = commandID
self.url = ""
self.name = name
self.lastUpdated = Timer()
if ipaddress and protocol:
self.url = "%s://%s:%s" % (protocol, ipaddress, port)
示例15: run
def run(self):
"""run
"""
all_greenlet = []
# 定时爬取
for group_url in self.group_list:
# timer = Timer(random.randint(0, self.interval), self.interval)
timer = Timer(random.randint(0, 2), self.interval)
greenlet = gevent.spawn(
timer.run, self._init_page_tasks, group_url)
all_greenlet.append(greenlet)
# 生产 & 消费
all_greenlet.append(gevent.spawn(self._page_loop))
all_greenlet.append(gevent.spawn(self._topic_loop))
# 重载代理,10分
proxy_timer = Timer(PROXY_INTERVAL, PROXY_INTERVAL)
all_greenlet.append(
gevent.spawn(proxy_timer.run(self.reload_proxies)))
gevent.joinall(all_greenlet)