为什么timeit不能用于我的代码片段?

时间:2014-06-04 17:53:31

标签: python ipython timeit

我认为这三个在逻辑上是等价的,返回集合{1, 3, 4}

set(sum(((1, 3), (4,), (1,)), ()))
set(sum([[1, 3], [4], [1]], []))
functools.reduce(operator.or_, ({1, 3}, {4}, {1}), set())

但是当我尝试在ipython(python 3.4.0上的v1.2.1)中检查每个的性能时,timeit magic失败了。

In [1]: from operator import or_; from functools import reduce

In [2]: timeit set(sum([[1, 3], [4], [1]], []))
1000000 loops, best of 3: 604 ns per loop

In [3]: timeit set(sum(((1, 3), (4,), (1,)), ()))
1000000 loops, best of 3: 330 ns per loop

In [4]: timeit reduce(or_, ({1, 3}, {4}, {1}), set())
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-83628f6293f3> in <module>()
----> 1 get_ipython().magic('timeit reduce(or_, ({1, 3}, {4}, {1}), set())')

/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2164         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2165         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2166         return self.run_line_magic(magic_name, magic_arg_s)
   2167 
   2168     #-------------------------------------------------------------------------

/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2085                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2086             with self.builtin_trap:
-> 2087                 result = fn(*args,**kwargs)
   2088             return result
   2089 

/usr/lib/python3/dist-packages/IPython/core/magics/execution.py in timeit(self, line, cell)

/usr/lib/python3/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    190     # but it's overkill for just that one bit of state.
    191     def magic_deco(arg):
--> 192         call = lambda f, *a, **k: f(*a, **k)
    193 
    194         if isinstance(arg, collections.Callable):

/usr/lib/python3/dist-packages/IPython/core/magics/execution.py in timeit(self, line, cell)
    929             number = 1
    930             for i in range(1, 10):
--> 931                 if timer.timeit(number) >= 0.2:
    932                     break
    933                 number *= 10

/usr/lib/python3.4/timeit.py in timeit(self, number)
    176         gc.disable()
    177         try:
--> 178             timing = self.inner(it, self.timer)
    179         finally:
    180             if gcold:

<magic-timeit> in inner(_it, _timer)

TypeError: unsupported operand type(s) for |: 'set' and 'tuple'

这里发生了什么?在2.7中也失败了。我无法使用vanilla python timeit.timeit方法重现这一点。

1 个答案:

答案 0 :(得分:4)

这在我看来是IPython中的一个错误。

首先是解决方法

转义大括号,以便调用看起来像

timeit reduce(or_, ({{1, 3}}, {{4}}, /usr/lib/python3/dist-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2085                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2086             with self.builtin_trap:
-> 2087                 result = fn(*args,**kwargs)
   2088             return result
), set())

现在问题

如果您看到调用堆栈,则在调用级联到timeit.py之前,它会通过

timeit

现在,如果您引用此源代码,您可以看到,在将参数传递给 magic_arg_s = self.var_expand(line, stack_depth) # Put magic args in a list so we can call with f(*a) syntax args = [magic_arg_s] 函数之前,将其格式化为在字符串中扩展Python变量

self.var_expand

DollarFormatter()调用class DollarFormatter(FullEvalFormatter): """Formatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments. 作为for-matter函数,其doc-string在以下行中说明了

reduce(or_, ((1, 3), 4, 1), set())

所以,这就是原因,集合被解释为标准的{foo}替换并被转换为元组(如果用逗号分隔的值)或一个使表达式为<的常量/ p>

{{1}}

这是偏离无效的。