簡體   English   中英

為什么timeit不能用於我的代碼片段?

[英]Why timeit doesn't work on my code snippet?

我認為這三個在邏輯上是等價的,返回集合{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方法重現這一點。

這在我看來是IPython中的一個錯誤。

首先是變通方法

逃避大括號,以便通話看起來像

timeit reduce(or_, ({{1, 3}}, {{4}}, {{1}}), set())

現在問題

如果你看到調用堆棧,在調用級聯到timeit.py之前,它會通過

/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

現在,如果您引用此源代碼,您可以看到,在將參數傳遞給timeit函數之前,將其格式化為在字符串中展開Python變量

        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]

self.var_expandDollarFormatter()調用為for-matter函數,其doc-string表示以下行中的內容

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. 

所以,這就是原因,一個集合被解釋為標准的{foo}替換並轉換為元組(如果用逗號分隔的值)或一個使表達式為

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

這是偏離無效的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM