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

2016-04-04 11:35:15 +08:00
 omg21
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))
3310 次点击
所在节点    Python
6 条回复
likuku
2016-04-04 11:51:25 +08:00
main() 最后一行,加个 break 呢?
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
2016-04-04 12:40:49 +08:00
不行啊,改名以后问题依旧, break 只能是用于循环语句中,加入后会提示语法错误。
omg21
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
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
2016-04-04 14:47:18 +08:00
print(times1.timeit(10000))
原来总是出在 10000 上,把 10000 改成 1 程序会运行 2 遍,改成 0 会运行 1 遍,但是时间不对。

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

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

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

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

© 2021 V2EX