Optimizing Inner Loop Copy

Michael Spencer mahs at telcopartners.com
Thu Aug 17 19:40:54 EDT 2006


Mark E. Fenner wrote:

> 
> and the copy is taking the majority (42%) of my execution time.
> So, I'd like to speed up my copy.  I had an explicit copy method that did
> what was needed and returned a new object, but this was quite a bit slower
> than using the standard lib copy.copy().
> 
How are you measuring? It seems to me that your Rule.copy method is a lot faster 
than copy.copy:

 >>> r=  Rule(range(100))
 >>> shell.timefunc(r.copy)
'copy(...)  36458 iterations, 13.71usec per call'
 >>> from copy import copy
 >>> shell.timefunc(copy, r)
'copy(...)  4498 iterations, 111.17usec per call'
 >>>


where shell.timefunc is:
def _get_timer():
     if sys.platform == "win32":
         return time.clock
     else:
         return time.time
     return

def timefunc(func, *args, **kwds):
     timer = _get_timer()
     count, totaltime = 0, 0
     while totaltime < 0.5:
         t1 = timer()
         res = func(*args, **kwds)
         t2 = timer()
         totaltime += (t2-t1)
         count += 1
     if count > 1000:
         unit = "usec"
         timeper = totaltime * 1000000 / count
     else:
         unit = "msec"
         timeper = totaltime * 1000 / count
     return "%s(...)  %s iterations, %.2f%s per call" % \
                 (func.__name__, count, timeper, unit)


Michael




More information about the Python-list mailing list