使 os.system('cls') 更快
Make os.system('cls') quicker
考虑以下代码:
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 window 变小以减少处理时间。有用!
生成和清除的像素较少使其成为理想的选择。
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 永远不可靠,但如果缩小 window,它就会接近。 (我认为它不必是现场。)
考虑以下代码:
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 window 变小以减少处理时间。有用! 生成和清除的像素较少使其成为理想的选择。
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 永远不可靠,但如果缩小 window,它就会接近。 (我认为它不必是现场。)