[Tutor] rounding up to the nearest multiple of 8

eryksun eryksun at gmail.com
Fri Oct 5 11:15:16 CEST 2012


On Fri, Oct 5, 2012 at 4:24 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> import timeit
> ver1 = timeit.timeit("""
> import math
> value = "1234"
> value = "%-*s" % (int(math.ceil(len(value)/8.0)*8), value)
> """)
> ver2 = timeit.timeit("""
> value = "1234"
> value = value.ljust( len(value) + (-len(value) % 8) )
> """)

Try to focus a timeit run on the code that would actually run in a
loop. Move global imports, constants, and class/function definitions
into one or more setup strings.

    >>> from timeit import timeit
    >>> setup = "from math import ceil; value = '1234'"

    >>> 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)

    >>> ver3 / ver2,  ver3 / ver1
    (0.6623768153526971, 0.2884886334856229)


More information about the Tutor mailing list