求教 timeit 正确用法

2018-12-15 01:42:44 +08:00
 youthfire

import timeit from timeit

def func(): xxx xxx func()

以前都是用 time.time 测试时间,可以成功测出。现在都说 timeit 测试小片断更方便,就想试试。

print(timeit(func(), number=1))

显示 raise ValueError("stmt is neither a string nor callable")

这个 func 明明可以正常运行的,为什么会无法 callable ?求教正确用法。

3605 次点击
所在节点    Python
10 条回复
ericls
2018-12-15 01:59:36 +08:00
fun 是 callable

func() 不是
youthfire
2018-12-15 02:02:08 +08:00
@ericls 没明白,只是一个函数名而已,就当作叫 abc 好了,abc 怎么就在 timeit 里不能 callable 了?
ericls
2018-12-15 03:03:21 +08:00
@youthfire abc 是 abc() 不是
Trim21
2018-12-15 03:25:17 +08:00
@youthfire #2 abc()是 adc 函数的返回值, 不是 callable 的, adc 是函数对象本事, 是 callable 的
ericls
2018-12-15 07:53:04 +08:00
楼上说得比较清楚
Outliver0
2018-12-15 08:20:41 +08:00
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
创建一个 Timer 实例,参数:
stmt (需要测量的语句或函数),
setup (初始化代码或构建环境的导入语句),
timer (计时函数),
number (每一次测量中语句被执行的次数)
如果在当前文件下测试函数的运行时间,setup:from __main__ import func
lxy
2018-12-15 09:29:19 +08:00
他的意思是直接传函数名 func,而不是 func(),后者是函数执行结果。还有你的 import 写反了。
www5070504
2018-12-15 11:12:10 +08:00
函数对象是可调用的 加上括号就变成了调用函数结果成了返回值了 abc 可调用 abc () 是 abc 函数的返回值 另外 from 在前边 这样看着真难受。。 作为 python 开发 这个格式还是要注意的 。。。
vonsdite
2018-12-15 11:15:13 +08:00
`timeit()`的`stmt`可以直接接受字符串的表达式, 也可以接受单个变量, 也可以接受函数。
接受函数的话, 你要传函数对象即 func, 你传 func()的话, 要将其设置为字符串表达式, 即"func()"

```python
import timeit

def func():
a = 'run func'

if __name__ == '__main__':
print(timeit.timeit(stmt=func, number=1)) # 这是传函数对象
print(timeit.timeit(stmt='func()', setup="from __main__ import func", number=1)) # 这是传字符串表达式
```


```python
def timeit(stmt="pass", setup="pass", timer=default_timer,
number=default_number, globals=None):
"""Convenience function to create Timer object and call timeit method."""
return Timer(stmt, setup, timer, globals).timeit(number)
```

https://vonsdite.cn/posts/6218c1b6.html 有例子,有说明
youthfire
2018-12-15 11:16:55 +08:00
感谢以上各位回复者,确实是这个问题,受教了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/517725

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX