1、for语句性能优于while
import time
if __name__ == '__main__':
start_time = time.time()
for i in range(10 ** 8):
pass
end_time = time.time()
run_time = end_time - start_time
print(run_time)
i = 0
start_time = time.time()
while i < 10 ** 8:
i += 1
end_time = time.time()
run_time = end_time - start_time
print(run_time)
运行结果:
2、max函数性能劣于直接判断:
import time
if __name__ == '__main__':
maxl = 0
start_time = time.time()
for i in range(10 ** 8):
maxl = max(maxl, i)
end_time = time.time()
run_time = end_time - start_time
print(run_time)
maxl = 0
start_time = time.time()
for i in range(10 ** 8):
if i > maxl: maxl = i
end_time = time.time()
run_time = end_time - start_time
print(run_time)
运行结果:
注:环境选用python3.9