Python's issue with callbacks

Posted by Ked on Tue 26 Aug 2003 04:35 PM — 1 posts, 5,519 views.

Russia #0
Having recently become completely disgusted with Vbscript, I've gone to testing Python with a purpose of figuring out performance benefits of translating about 2k lines of code into that language. After fidling with a code snippet, found in Python's newsgroup, I arrived at a few trivial conclusions: Python is faster than Vbscript by alot when it comes to math, it has less overhead associated with function calls than Vbscript does, not to mention that it is by far more powerful and flexible than Microsoft's little victim of incest (although that victim did serve me well for awhile). About the only thing at which Python fails misearably when compared to Vbscript is Mushclient's callbacks. Unfortunately, it's 1.5-4.5 times slower than Vbscript when it comes to using callbacks. Although I couldn't figure out a way to make Python outrun Vbscript on callbacks, I can offer a little advice for making sure you squeeze as much out of Python when doing World.Note's, or any other callback routines, as possible. Compare the following two functions:


from time import clock
aggregateTime = 0.0

def Main(name, output, wildcs):
  global aggregateTime
  list = range(100)
  for i in list:
      startTime = clock()           # timing starts here
      lworldEnTrig = world.EnableTrigger
      lworldEnTrig("test_callbacks", 1)
      lworldEnTrig("test_callbacks", 0)
      totalTime = clock() - startTime   # timing ends here
      aggregateTime = aggregateTime + totalTime 
  averageTime = aggregateTime/100
  world.Note("Average time (mapped version): " + str(averageTime))
  aggregateTime = 0.0      


and


from time import clock
aggregateTime = 0.0

def Main(name, output, wildcs):
  global aggregateTime
  list = range(100)
  for i in list:
      startTime = clock()      # timing starts here
      world.EnableTrigger("test_callbacks", 1)
      world.EnableTrigger("test_callbacks", 0)
      totalTime = clock() - startTime   # timing ends here
      aggregateTime = aggregateTime + totalTime 
  averageTime = aggregateTime/100
  world.Note("Average time (mapped version): " + str(averageTime))
  aggregateTime = 0.0      


The former code has
World.EnableTrigger
callback mapped to a local object
lworldEnTrig
. Even though there's one extra instruction in
the first snippet, its'
For
loop executes 1.5-2 times faster than the one in the latter function. Though you'd need a microscope to notice the performance gain in the above example, it can become quite noticable if you are
using lots of callbacks in your code. Besides, you could get into a habbit of mapping callbacks locally in your functions anyway - it'll speed up your script in the long run, and there's no reason for not getting some extra speed at the cost of a few more lines of code and a little bit of memory.