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


有人能在这方面帮我吗?任何对这些问题的建议都将受到高度赞赏。
发布于 2018-09-03 07:52:57
其他人已经解决了主要问题(您传递给timeit()的代码无效),我只想提到,使用通常发布的解决方案(在两个语句之间添加一个分号),您最终将对这两个语句的总成本进行基准测试(创建文字字符串"Hello world",将其分配给变量,并对该变量调用endswith('d') )。假设您真正感兴趣的只是第二条语句的成本,您可能希望使用timeit()第二条(可选)“安装”参数,这是在执行测试代码之前要执行的一段代码,即:
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")发布于 2018-09-03 06:34:20
我猜您在python中没有那么多的编程经验,否则SyntaxError就足够清晰了。给出的异常声明语法(即。代码行)无效。
有效的(复合语句)代码。但更难读,所以不建议:
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发布于 2018-09-03 06:56:25
如果您想运行几个语句,您可以简单地使用三元引号作为您的代码。示例:
import timeit
code = """
s = 'Hello world'
s.endswith('d')
"""
timeit.timeit(code, number=10000)https://stackoverflow.com/questions/52144105
复制相似问题