Passing function objects to timeit
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sat Mar 29 23:27:45 EDT 2008
En Sat, 29 Mar 2008 23:23:07 -0300, Steven D'Aprano
<steve at REMOVE-THIS-cybersource.com.au> escribió:
> The general problem is that I wish to time an arbitrary function with
> arbitrary arguments. The function and arguments are provided to me as
> Python objects, but timeit requires strings. Converting the objects to
> strings is not practical, and the objects might not exist in the __main__
> module.
Ah, ok, I understand now. I think this is more-or-less what you want:
py> def test1(s):
... return len(s)
...
py> def test2(s):
... return s.__len__()
...
py> from timeanyfunc import timeanyfunc
py> timeanyfunc(test1, [1,2,3])
[1.3858088108963571, 1.3810702198184406, 1.3818543976957964]
py> timeanyfunc(test2, [1,2,3])
[1.6241321173501095, 1.6240804348038651, 1.6195021993018663]
<code>
# timeanyfunc.py
from timeit import Timer
def timeanyfunc(fn, *args, **kw):
global wrapped_fn
def wrapped_fn():
return fn(*args, **kw)
return Timer("wrapped_fn()",
"from %s import wrapped_fn" % __name__
).repeat()
</code>
--
Gabriel Genellina
More information about the Python-list
mailing list