Can you make this faster?

"Martin v. Löwis" martin at v.loewis.de
Sun Jun 27 17:22:41 EDT 2004


Kamilche wrote:
> I have a routine that I really need, but it slows down processing
> significantly. Can you spot any ineffeciencies in the code?

I would use a dictionary, and I would pre-allocate the result list:

_code = {types.StringType:  's',
          types.IntType:     'i',
          types.LongType:    'q',
          types.BooleanType: 'c',
          types.FloatType:   'd'
         }
def fmtstring(args):
     fmt = ['\0']*(len(args)+1)
     fmt.append('<')
     for i, arg in enumerate(args):
         t = type(arg)
         try:
             c = _code[t]
         except KeyError:
             raise Exception("Can't pack argument of type %s!" % t)
         if c == 's':
             fmt[i] = str(len(arg))+'s'
         else:
             fmt[i] = c
     return ''.join(fmt)

Regards,
Martin




More information about the Python-list mailing list