python timeit Timer比较两个程序的运行时间


from timeit import Timer

def checkword01(word1,word2):
    lettercounter1=[0]*26
    lettercounter2=[0]*26
    for i in range(len(word1)):
        pos=ord(word1[i])-ord("a")
        lettercounter1[pos]+=1
    for i in range(len(word2)):
        pos=ord(word2[i])-ord("a")
        lettercounter2[pos]+=1  
    flag=False
    if lettercounter1==lettercounter2:
        flag=True
    return flag

        
def checkword02(word1,word2):
    wordlist01=list(word1)
    wordlist02=list(word2) 
    worddict01={}
    worddict02={}
    for i in wordlist01:
        if i not in worddict01: 
            worddict01[i]=0
        else:
            worddict01[i]+=1
    for i in wordlist02:
        if i not in worddict02: 
            worddict02[i]=0
        else:
            worddict02[i]+=1
    flag=True  
   
    if len(worddict01)!=len( worddict02):        
        flag=False
        return
    for key in worddict01:
        if key not in worddict02:           
            flag=False
            return flag
        else:
            if worddict01[key]!=worddict02[key]:                
                flag=False
                return flag
    return flag          
   

ret01=checkword01("pythoon","typhoon")   
ret02=checkword02("pythoon","typhoon")
print(ret01)
print(ret02)
t1= Timer('checkword01("pythoon","typhoon")', 'from __main__ import checkword01')
t2 = Timer('checkword02("pythoon","typhoon")', 'from __main__ import checkword02')
print(t1.timeit(number=1000))
print(t2.timeit(number=1000))

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值