又仔细测试了一下 代码如下
>>> from time import sleep, ticks_us as ticks
run_times=1
def test1():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
if x1!=x2 and x1!=x3:
x1=x3
x4=x4+1
t2=ticks()
print(t2-t1)
def test2():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
q=(x1^x2)&(x1^x3)
x1=x1^q
x4=x4+q
t2=ticks()
print(t2-t1)
sleep(1)
test1()
sleep(1)
test2()
32
15
>>> from time import sleep, ticks_cpu as ticks
run_times=1
def test1():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
if x1!=x2 and x1!=x3:
x1=x3
x4=x4+1
t2=ticks()
print(t2-t1)
def test2():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
q=(x1^x2)&(x1^x3)
x1=x1^q
x4=x4+q
t2=ticks()
print(t2-t1)
sleep(1)
test1()
sleep(1)
test2()
5010
2246
>>> from time import sleep, ticks_cpu as ticks
run_times=10
def test1():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
if x1!=x2 and x1!=x3:
x1=x3
x4=x4+1
t2=ticks()
print(t2-t1)
def test2():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
q=(x1^x2)&(x1^x3)
x1=x1^q
x4=x4+q
t2=ticks()
print(t2-t1)
sleep(1)
test1()
sleep(1)
test2()
16096
12813
>>> from time import sleep, ticks_cpu as ticks
run_times=100
def test1():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
if x1!=x2 and x1!=x3:
x1=x3
x4=x4+1
t2=ticks()
print(t2-t1)
def test2():
t1=ticks()
for i in range(run_times):
x1=0
x2=1
x3=1
x4=0
q=(x1^x2)&(x1^x3)
x1=x1^q
x4=x4+q
t2=ticks()
print(t2-t1)
sleep(1)
test1()
sleep(1)
test2()
126486
119600
>>>循环次数增加 感觉逐渐拉平
在电脑上 使用time_ns代替ticks_xxx 循环100000次 是37:64 (ms) 是if判断更快
另外一个测试 这里难以完全描述 是在整个系统里的实际应用临时增加一个计时 对运行时间进行累加和平均 使用if判断又反而比运算法来得快 大概耗时比是94:116
最终决定 还是用回if法