谁是最快的:for,while,str.count

时间:2014-02-18 14:18:57

标签: python

#1st solution 
m = num 
cnt = 0 
while m>0: 
   if m%10 == 0: 
       cnt = cnt+1 
   m = m//10 

#2nd solution 
cnt =0 
snum = str(num) 
for digit in snum: 
    if digit == "0": 
        cnt = cnt+1 

#3rd solution 
cnt = str.count(str(num), "0")

使用time.clock(),(为每个解决方案找到t1-t2)似乎总是for是最快的是吗?为什么会这样?

1 个答案:

答案 0 :(得分:1)

显然str(num).count('0')是最好的。

使用timeit进行基准测试:

In [303]: timeit str(num).count('0')
1000000 loops, best of 3: 1.38 us per loop

In [304]: %%timeit
     ...: m = num
     ...: cnt = 0
     ...: while m > 0:
     ...:     if m % 10 == 0:
     ...:         cnt = cnt+1
     ...:     m = m // 10
     ...: 
100000 loops, best of 3: 13.6 us per loop

In [306]: %%timeit
     ...: cnt = 0
     ...: snum = str(num)
     ...: for digit in snum:
     ...:     if digit == '0':
     ...:         cnt +=1
     ...: 
100000 loops, best of 3: 4.11 us per loop