V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
rogwan
V2EX  ›  Python

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

  •  
  •   rogwan · 2017-07-13 18:48:57 +08:00 · 3546 次点击
    这是一个创建于 2479 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如:

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

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

    10 条回复    2017-07-15 23:15:35 +08:00
    zhusimaji
        1
    zhusimaji  
       2017-07-13 18:57:24 +08:00 via iPhone
    使用 time 模块就好了
    ranleng
        2
    ranleng  
       2017-07-13 20:25:00 +08:00
    开头一时间
    结束一时间
    然后相减(?)
    ech0x
        3
    ech0x  
       2017-07-13 21:43:43 +08:00 via iPad
    第一反应也是连个 time 相减
    est
        4
    est  
       2017-07-13 21:52:39 +08:00
    line_profile
    4ever911
        5
    4ever911  
       2017-07-13 21:57:47 +08:00   ❤️ 1
    ipython


    %timeit 最简单了
    csuzhangxc
        6
    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
        7
    csuzhangxc  
       2017-07-13 22:50:23 +08:00   ❤️ 2
    官方文档:timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
    csuzhangxc
        8
    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
        9
    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
        10
    ridaliu  
       2017-07-15 23:15:35 +08:00
    如果用 ipython 的话,可以开启自动监测运行时间的功能
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2802 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 03:57 · PVG 11:57 · LAX 20:57 · JFK 23:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.