Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Using Ao_timer for a better sleep

A few of my old examples include 'unsafe' use of e32.ao_sleep().
The problem is that the sleep can't be interrupted.
I often use a convenient loop like this
   1  
   2  while running:
   3    // do something
   4    e32.ao_sleep(1)  # sleep a sec


Now in pys60 1.3.1, it's better to use e32.Ao_timer
   1  
   2  timer = e32.Ao_timer()
   3  while running:
   4    // do something
   5    timer.after(1)   # sleep a sec

I can then interupt the sleep with
   1  timer.cancel()

in other part of the program if I need to continue the loop.

For example, I can end the application without waiting for
the last second.

Mobile timer app

   1  
   2  from appuifw import *
   3  from key_codes import *
   4  import e32, time
   5  
   6  class StopWatch:
   7      running = 0
   8      time_start = None
   9      elap = 0.0
  10  
  11      def __init__(self):
  12          self.canvas = Canvas(self.update)
  13          app.body = self.canvas
  14          self.canvas.bind(EKeySelect, self.toggle)
  15          self.update()
  16  
  17      def update(self, rect=None):
  18          if self.running:
  19              self.elap = time.clock() - self.time_start
  20              e32.ao_sleep(0.05, self.update)
  21          t = self.elap
  22          min = int(t / 60)
  23          sec =  int(t - min*60)
  24          hsec = int((t - min*60 - sec)*100)
  25          self.canvas.clear()
  26          self.canvas.text((20,40), u"%02d:%02d:%02d" % (min,sec,hsec), font='title')
  27  
  28      def toggle(self):
  29          if self.running:
  30              self.running = 0
  31              self.elap = time.clock() - self.time_start
  32          else:
  33              self.running = 1
  34              self.time_start = time.clock() - self.elap
  35              self.update()
  36  
  37      def reset(self):
  38          self.running = 0
  39          self.elap = 0.0
  40          self.update()
  41  
  42  
  43  sw = StopWatch()
  44  lock = e32.Ao_lock()
  45  app.menu = [(u'Reset', sw.reset), (u'Close', lock.signal)]
  46  app.exit_key_handler = lock.signal
  47  lock.wait()

This will run and pause, resume when you press the select key.

Use timeit module

   1  
   2  >>> from timeit import Timer
   3  >>> t = Timer('md5.new("md5 is not safe").digest()', 'import md5')
   4  >>> t.timeit()
   5  2.6892227922821803

Quite useful to compare speed of codes.
Read more here
http://diveintopython.org/performance_tuning/timeit.html
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS