推荐学习书目
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 · Jul 13, 2017 · 4313 views
    This topic created in 3228 days ago, the information mentioned may be changed or developed.

    比如:

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

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

    10 replies    2017-07-15 23:15:35 +08:00
    zhusimaji
        1
    zhusimaji  
       Jul 13, 2017 via iPhone
    使用 time 模块就好了
    ranleng
        2
    ranleng  
       Jul 13, 2017
    开头一时间
    结束一时间
    然后相减(?)
    ech0x
        3
    ech0x  
       Jul 13, 2017 via iPad
    第一反应也是连个 time 相减
    est
        4
    est  
       Jul 13, 2017
    line_profile
    hihihihihi
        5
    hihihihihi  
       Jul 13, 2017   ❤️ 1
    ipython


    %timeit 最简单了
    csuzhangxc
        6
    csuzhangxc  
       Jul 13, 2017
    timeit.timeit("if x in list1: pass", "x='aaa'; list1=['aaa', 'bbb', 'ccc', 'ddd', 'eee']")
    csuzhangxc
        7
    csuzhangxc  
       Jul 13, 2017   ❤️ 2
    官方文档:timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
    csuzhangxc
        8
    csuzhangxc  
       Jul 13, 2017
    你如果要看一次
    timeit.timeit("if x in list1: pass", "x='aaa'; list1=['aaa', 'bbb', 'ccc', 'ddd', 'eee']", number=1)
    不过一般不这样干吧。。。
    yucongo
        9
    yucongo  
       Jul 14, 2017
    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  
       Jul 15, 2017
    如果用 ipython 的话,可以开启自动监测运行时间的功能
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3034 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 06:26 · PVG 14:26 · LAX 23:26 · JFK 02:26
    ♥ Do have faith in what you're doing.