gpt4 book ai didi

python - 为什么 timeit.timeit 在使用变量时会出错?

转载 作者:行者123 更新时间:2023-11-30 22:08:31 26 4
gpt4 key购买 nike

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

Using Value inside timeit

有人可以在这方面帮助我吗?非常感谢对这些问题的任何建议。

最佳答案

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

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

它将执行两个语句,但仅对第一个语句进行基准测试。

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

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

或者从当前脚本或交互式 shell session :

$ 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")

关于python - 为什么 timeit.timeit 在使用变量时会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52144105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com