m24h作者
2年6个月前IP:上海
931464
4楼

又仔细测试了一下 代码如下

>>> 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法 

评论
文号 / 931464

千古风流
名片专栏发私信
学术分 1
总主题 68 帖总回复 1007 楼拥有证书:进士 学者 机友
注册于 2020/01/22 18:44:43最后登录 2026/10/31 02:54:58
主体类型:个人
所属领域:无
认证方式:手机号
IP归属地:上海

个人简介

个人开源项目: m24h.github.io

笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的