我的编程基础老师在她的一堂课上说过,使用“break”或“continue”关键字的效率低于使用布尔值退出循环的效率。
我编写并运行了一个用 Python 编写的程序,看看是否是这种情况:
import time;
TIMES = 100000000
COMPARE_FROM = "foo"
COMPARE_TO = "roo"
def breakTest() :
while(True) :
break;
if(COMPARE_FROM == COMPARE_TO) :
boo = "boo"
def booleanTest() :
running = True;
while(running) :
running = False;
if(running):
if(COMPARE_FROM == COMPARE_TO) :
boo = "boo"
def main() :
breakTimeBefore = 0;
breakTimeAfter = 0;
booleanTimeBefore = 0;
booleanTimeAfter = 0;
print("running break test ...");
breakTimeBefore = time.time();
for i in range(0, TIMES, 1):
breakTest();
breakTimeAfter = time.time();
print("break test complete");
print("Time: %f seconds \n" % (breakTimeAfter - breakTimeBefore));
print("running boolean test ...");
booleanTimeBefore = time.time();
for i in range(0, TIMES, 1):
booleanTest();
booleanTimeAfter = time.time();
print("boolean test complete");
print("Time: %f seconds \n" % (booleanTimeAfter - booleanTimeBefore))
print("---- FINDINGS ----");
print("breakTest time: %f" % (breakTimeAfter - breakTimeBefore));
print("booleanTest time: %f" % (booleanTimeAfter - booleanTimeBefore));
print("diffrence: %f" % ((breakTimeAfter - breakTimeBefore) - (booleanTimeAfter - booleanTimeBefore)));
input("Press enter to close...");
main();
在运行了 3 次并对结果进行平均后,我发现 breakTest 快了 6.25 秒。
那么 break 关键字更有效还是我的代码错误?