请考虑以下代码:
import time
import os
for a in range(10, 0, -1): # total time is actually 1 second. no float allowed for arg 3.
print(a)
time.sleep(0.X) #unknown time...
os.system('cls')
在程序开始时,a
每次减少1/10秒。
问题:os.system('cls')
的处理时间超过0.1秒。有什么解决方案可以使其更快?
我知道您的问题是for循环运行了1秒钟以上,因为os.system('cls')
不是瞬时的:
您可以通过使用Python中的timeit
模块进行测试:
没有os.system('cls')
:
import time
import timeit
import os
start = timeit.default_timer()
for a in range(10, 0, -1): # total time is actually 1 second. no float allowed for arg 3.
print(a)
time.sleep(0.1) #unknown time...
stop = timeit.default_timer()
print('Time: ', stop - start)
输出:
10
9
8
7
6
5
4
3
2
1
Time: 1.0021432
使用os.system('cls')
:
Time: 1.7151739000000001
您无法解决此问题,因为即使没有os.system('cls')
,也要花费超过1秒钟的时间。函数os.system('cls')
本身已经花费了大约0.1649219
秒来执行。您无法使Python库功能更快。
实际上,您可以使cmd窗口变小以减少处理时间。有用!较少的像素可以生成和清除,使其成为理想的选择。
def count():
for a in range(10, 0, -1):
print(a)
time.sleep(0.1) #I know I am breaking the DO NOT USE TIME.SLEEP rule.
os.system('cls')
count()
如上所述,使用time.sleep永远都不可靠,但是如果您缩小窗口,它就会关闭。 (我认为它不一定是必需的。)