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
omg21
V2EX  ›  Python

把主程序加到 main()中就无限循环了,应该怎么处理呢?

  •  
  •   omg21 · 2016-04-04 11:35:15 +08:00 · 3296 次点击
    这是一个创建于 2955 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def a2(Url):
    #......
    return NameList

    if __name__ =="__main__":
    #......
    print('处理完毕!')


    本来上边这段代码运行的好好的(请无示省略号),后来我想测试一下每次运行需要花费多长时间,于是加了一个计时模块,把主程序定义成一个函数,代码如下所示,然后再运行的时候主程序就循环运行了,只要运行一遍就行了,应该怎么处理呢?

    def a2(Url):
    #......
    return NameList

    def main():
    #......
    print('处理完毕!')


    if __name__ =="__main__":
    main()

    #运行时间计时
    import timeit
    times1=timeit.Timer("main()","from __main__ import main")
    print(times1.timeit(10000))
    6 条回复    2016-04-04 14:47:18 +08:00
    likuku
        1
    likuku  
       2016-04-04 11:51:25 +08:00
    main() 最后一行,加个 break 呢?
    likuku
        2
    likuku  
       2016-04-04 11:58:29 +08:00
    你何不将 def mian(): 改名为 def test_main():

    if __name__ =="__main__":
    #main()

    #运行时间计时
    import timeit
    times1=timeit.Timer("test_main()","from __main__ import test_main")
    print(times1.timeit(10000))
    omg21
        3
    omg21  
    OP
       2016-04-04 12:40:49 +08:00
    不行啊,改名以后问题依旧, break 只能是用于循环语句中,加入后会提示语法错误。
    omg21
        4
    omg21  
    OP
       2016-04-04 12:45:30 +08:00
    刚才又试了一下,把这三行去掉,问题就不存在了,程序只运行一遍即结束,看来问题是出在 timeit 的调用上。
    import timeit
    times1=timeit.Timer("test_main()","from __main__ import test_main")
    print(times1.timeit(10000))
    sNullp
        5
    sNullp  
       2016-04-04 12:48:44 +08:00
    LMGTFY: https://docs.python.org/3.0/library/timeit.html

    Timer.timeit([number=1000000])
    Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.
    omg21
        6
    omg21  
    OP
       2016-04-04 14:47:18 +08:00
    print(times1.timeit(10000))
    原来总是出在 10000 上,把 10000 改成 1 程序会运行 2 遍,改成 0 会运行 1 遍,但是时间不对。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4098 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:13 · PVG 13:13 · LAX 22:13 · JFK 01:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.