检查某一条语句执行花了多少时间,用 timeit 怎么查看?

2017-07-13 18:48:57 +08:00
 rogwan

比如:

list1 = [ 'aaa', 'bbb', 'ccc, 'ddd',  'eee' ]
if x in list1:
    pass

想要监测系统在执行过程中,上面这条 if 语句执行消耗了多少时间,用 timeit 怎么查看?

3559 次点击
所在节点    Python
10 条回复
zhusimaji
2017-07-13 18:57:24 +08:00
使用 time 模块就好了
ranleng
2017-07-13 20:25:00 +08:00
开头一时间
结束一时间
然后相减(?)
ech0x
2017-07-13 21:43:43 +08:00
第一反应也是连个 time 相减
est
2017-07-13 21:52:39 +08:00
line_profile
4ever911
2017-07-13 21:57:47 +08:00
ipython


%timeit 最简单了
csuzhangxc
2017-07-13 22:46:59 +08:00
timeit.timeit("if x in list1: pass", "x='aaa'; list1=['aaa', 'bbb', 'ccc', 'ddd', 'eee']")
csuzhangxc
2017-07-13 22:50:23 +08:00
官方文档:timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
csuzhangxc
2017-07-13 22:51:34 +08:00
你如果要看一次
timeit.timeit("if x in list1: pass", "x='aaa'; list1=['aaa', 'bbb', 'ccc', 'ddd', 'eee']", number=1)
不过一般不这样干吧。。。
yucongo
2017-07-14 00:42:49 +08:00
In [6]: %paste
import timeit

setup = "list1 = [ 'aaa', 'bbb', 'ccc', 'ddd', 'eee' ]"
stmt = "if 'x' in list1: pass"
t = timeit.Timer(stmt=stmt, setup=setup)

n = 1
print("{0:.3f}".format(t.timeit(number=n)/n))

n = 10
print(t.timeit(number=n)/n)

n = 10000
print(t.timeit(number=n)/n)

n = 1000000
print(t.timeit(number=n)/n)

## -- End pasted text --
0.000
1.3518072108809065e-06
8.570457728040992e-07
1.0187274455574879e-06
ridaliu
2017-07-15 23:15:35 +08:00
如果用 ipython 的话,可以开启自动监测运行时间的功能

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

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

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

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

© 2021 V2EX