Can you make this faster?

William Park opengeometry at yahoo.ca
Mon Jun 28 03:41:21 CEST 2004


Kamilche <klachemin at home.com> wrote:
> I have a routine that I really need, but it slows down processing
> significantly. Can you spot any ineffeciencies in the code?
> 
> This code makes a critical function of mine run about 7x slower than
> using a prebuilt format string. For maximum flexibility, it would be
> best to calculate the format string using this method, so I'd dearly
> love to keep it.
> 
> def fmtstring(args):
>     delim = '\0'
>     fmt = []
>     fmt.append('<')
>     for arg in args:
>         t = type(arg)
>         if t == types.StringType:
>             l = len(arg)
>             fmt.append(str(l) + 's')
>         elif t == types.IntType:
>             fmt.append('i')
>         elif t == types.LongType:
>             fmt.append('q')
>         elif t == types.BooleanType:
>             fmt.append('c')
>         elif t == types.FloatType:
>             fmt.append('d')
>         else:
>             raise Exception("Can't pack argument of type %s!" % t)
>     s = ''.join(fmt)
>     s = s + '\0'
>     return s

String concatenation ('+') is main culprit.  Avoid it. 

    Before		After
    ------		-----
    str(l) + 's'	fmt.append (str(l))
			fmt.append ('s')
    
    s = ''.join(fmt)	fmt.append ('\0')
    s = s + '\0'	''.join(fmt)
    
-- 
William Park, Open Geometry Consulting, <opengeometry at yahoo.ca>
Q: What do you use to remove bugs on Windows?  A: Windex.



More information about the Python-list mailing list