New restrain builtin function?

Robert Brewer fumanchu at amor.org
Sun Mar 21 17:15:25 EST 2004


I wrote a bunch of guff about limit(), including:
> If you had a dataset with many large iterables, you would probably go
> ahead and incur the overhead of an inner function call, with something
> like:
> 
> def limit3(obj, lower=None, upper=None):
>     if upper is None:
>         if lower is None:
>             limfunc = lambda i: i
>         else:
>             def _lower(i):
>                 if i < lower:
>                     i = lower
>                 return i
>             limfunc = _lower
>     else:
>         if lower is None:
>             def _upper(i):
>                 if i > upper:
>                     i = upper
>                 return i
>             limfunc = _upper
>         else:
>             def _both(i):
>                 if i < lower:
>                     i = lower
>                 if i > upper:
>                     i = upper
>                 return i
>             limfunc = _both
>     
>     if hasattr(obj, '__iter__'):
>         product = []
>         for item in obj:
>             product.append(limfunc(item))
>         return product
>     else:
>         return limfunc(obj)
> 
> ...which might squeeze a bit of performance out of the partial
> application:
> 
> >>> tl = timeit.Timer("limit.limit(data, 1, 5)", "import limit; data =
> (0, 3, 6) * 100")
> >>> tl.timeit(10000)
> 7.1556577721471513
> >>> t3l = timeit.Timer("limit.limit3(data, 1, 5)", "import 
> limit; data =
> (0, 3, 6) * 100")
> >>> t3l.timeit(10000)
> 5.0156802051656086

Of course, I tested the wrong function (I should have tested "limit4"
instead of "limit"). Turns out the partial application solution
("limit3") is slower after all:

>>> t4l = timeit.Timer("limit.limit4(data, 1, 5)", "import limit; data =
(0, 3, 6) * 100")
>>> t4l.timeit(10000)
3.8564284008166396
>>> t3l.timeit(10000)
4.9950809390575159

Meh. It was fun trying.


FuManChu




More information about the Python-list mailing list