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)
This is only if Statement , give the result as follows :
add else Statement rule :
In general , The first branch saves time . The second branch will take a little more time .