import timeit
def func1():
for i in range(100000):
if i > 0:
k = 2
def func2():
for i in range(100000):
if i < 0:
k = 2
def func3():
for i in range(100000):
if i == 0:
k = 2
def func4():
for i in range(100000):
if i != 0:
k = 2
def func5():
for i in range(100000):
if i >= 0:
k = 2
def func6():
for i in range(100000):
if i <= 0:
k = 2
if __name__ == '__main__':
func1()
func=[func1,func2,func3,func4,func5,func6]
op = [">","<","==","!=",">=","<="]
for j in range(6):
v = 0
timer = timeit.Timer(func[j])
v+= timer.timeit(number=1000)
print(op[j],":",v)
這是只有if語句的情況,結果如下:
加上else語句則:
一般情況下,第一個分支比較節省時間。第二個分支會耗時稍微多一些。