On 10/05/2012 07:23 AM, Albert-Jan Roskam wrote: > ----- Original Message ----- > >> From: Asokan Pichai <paso...@talentsprint.com> >> To: tutor@python.org >> Cc: >> Sent: Friday, October 5, 2012 11:06 AM >> Subject: Re: [Tutor] rounding up to the nearest multiple of 8 >> >> If you are doing so many times, it may be worth precomputing the padding for >> a >> given length and adding it by a look up on the length. >> >> For example: >> ------------------------ >> SPACE = ' ' >> MAX = 1000 >> TAB = 8 >> paddding = [ SPACE * (n % TAB) for n in range(MAX) ] >> >> ..... >> s = padding[len(s)] + s >> ..... >> -------------------------- >> where s is string to be padded >> >> Asokan Pichai > > Good idea! I know that the string values can never exceed 32767 bytes. So > when I combine all the advice I got here, the best way seems to be ver4, > using Eryksun's ver3 to initialize a dictionary: > > from timeit import timeit > setup = "from math import ceil; value = 1040 * '*'" > setup += "; " + "padLookup = dict([(i, -8 * (i // -8)) for i in range(1, > 32767+1)])" > ver1 = timeit('int(ceil(len(value)/8.0)*8)', setup=setup) > ver2 = timeit('len(value) + (-len(value) % 8)', setup=setup) > ver3 = timeit('-8 * (len(value) // -8)', setup=setup) > ver4 = timeit('padLookup[len(value)]', setup=setup) > > print ver1/ver4, ver2/ver4, ver3/ver4, ver4/ver4 > > Thanks guys! >
This is all fun, but what about the context? Your original function took an integer, not a string, and thus wasn't charged with measuring string length, possibly multiple times. Even so, each of these tests is taking around a microsecond. So are you expecting to do anything with the result? Just calling ljust() method more than doubled the time. If you actually have some code to generate the string, and/or if you're going to take the result and write it to a file, then pretty soon this function is negligible time. If it were my code, i think I'd use something like " "[-sz%8:] and either prepend or append that to my string. But if I had to do something more complex, I'd tune it to the way the string were being used. -- DaveA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor