为什么 timeit.timeit 在使用 with 变量时出错?

Why timeit.timeit is giving error when using with variable?

我一直在尝试执行一个代码片段以了解执行需要多少时间。 我曾尝试过两种选择来做到这一点。一种是在 timeit.timeit 函数中使用变量并进行检查。另一种是直接使用值和检查。 第二种方法工作正常,但我在使用第一种方法时遇到了一些范围界定问题。附件是两种情况的图像。

谁能在这方面帮助我?非常感谢对问题的任何建议。

问题是 s = 'Hello World's.endswith('d')

是两个单独的语句,因此它们要么必须在不同的行中,要么必须使用分号分隔

所以改成

timeit.timein("s = 'Hello World'; s.endswith('d')",number=10000)

我猜你在 python 方面没有太多编程经验,否则 SyntaxError 就足够清楚了。给出的异常表明语法(即代码行)无效。

有效(Compound statement)代码。但更难阅读所以不建议:

s='Hello world'; s.endswith('d')

无效代码:

s='Hello world'  s.endswith('d')

后者会引发异常,它会尝试用“^”突出显示异常发生的确切位置。

s='Hello world'  s.endswith('d')
  File "<stdin>", line 1
    s='Hello world'  s.endswith('d')
                     ^
SyntaxError: invalid syntax

为了使用 timeit 测试少量代码,您可以将代码放入一个函数中并调用它。例如:

import timeit

def test():
    s = 'Hello world'
    s.endswith('d')


if __name__ == '__main__':
    t = timeit.Timer('test()', setup='from __main__ import test')
    num_of_repeat = 1000
    runs = t.repeat(repeat=num_of_repeat, number=1)
    print('Fastest run of {3} repeats: {0}ms  Slowest: {1}ms  Average: {2}ms'.format(
        min(runs) * 1000, max(runs) * 1000, (sum(runs) / float(len(runs))) * 1000, num_of_repeat))

将其放入名为 mytest.py 的文件中,并从命令行 运行 将其放入:

python mytest.py

如果您想要 运行 多个语句,您只需在代码中使用三重引号即可。示例:

import timeit
code = """
s = 'Hello world'
s.endswith('d')
"""
timeit.timeit(code, number=10000)

其他人已经解决了主要问题(您传递给 timeit() 的代码无效),我只是想提一下,使用通常发布的解决方案(在两个语句之间添加分号)您将最终对两个语句组合的总成本进行基准测试(创建文字字符串 "Hello world",将其分配给一个变量并对该变量调用 endswith('d'))。假设您真正感兴趣的只是第二条语句的成本,您可能希望使用 timeit() 第二个(可选)"setup" 参数和一段要执行的代码 before执行测试代码,即:

import timeit
timeit.timeit("s.endwith('d')", "s = 'Hello World'", number=10000)

这将执行两个语句但只对第一个进行基准测试。

如果您想对从模块导入的函数进行基准测试,这也很有用:

timeit.timeit("re.search(r'42', 'hello world')", "import re")

或来自您当前的脚本或交互式 shell 会话:

$ python
Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
>>>    return 42
>>> import timeit
>>> timeit.timeit("foo()", "from __main__ import foo")