%timeit 是否通过命令行中的参数应用于函数或引用?

Is %timeit applied to a function or reference via parameters in command line?

我正在遵循建议 运行ning %timeit following 的指南,其中 following 是定义的函数。

我试过使用 import timeit,但由于某些原因 %timeit 没有 运行。我收到一个语法错误,很明显我没有正确使用它。我做了一个简短的搜索,在 timeit 库中找到了页面,但这让我在使用方面更加困惑。

我怀疑你混淆了 %timeittimeit:

  • %timeit 是一个 IPython "magic" 命令,只能在 IPython shell 会话中使用。示例用法为:

    In [1]: %timeit myfunc()
    
  • timeit 是标准 Python 模块 - 您可以在脚本中 import timeit,并使用 timeit.timeit("expression") 等。参见 the documentation 了解全部详情。


这是一个示例,展示了您可以在 IPython 会话中使用 timeit.timeit 的一种方式:

In [2]: def foo(): pass

In [3]: import timeit

In [4]: timeit.timeit("foo()", setup="from __main__ import foo", number=10000)
Out[4]: 0.004509925842285156

在这种情况下,我们的函数 foo 是在 IPython 会话的全局命名空间中定义的,因此我们从 __main__ 导入它。如果它是在某个外部模块中定义的,则有必要修改 import 语句以反映这一点,例如:

In [5]: timeit.timeit("pow(10, 3)", setup="from math import pow", number=10000)
Out[5]: 0.00642085075378418

这里我从 math 模块导入 pow 函数。

要尝试用 timeit 从 IPython 的魔法中重现 %timeit,试试这个:

timeit.Timer(my_function).repeat(3, 1000)

%timeit 在执行 n 次时取 3 次中的最佳次数,其中 n 是内部选择的(因此 repeat() 中的 1000 可能不是一个好的选择)

reference:

-n N: execute the given statement N times in a loop. If this value is not given, a fitting value is chosen.

-r R: repeat the loop iteration R times and take the best result. Default: 3