ipython中可以执行魔术方法%timeit
检查输入手机号是否为同一个数字
In [27]: a
Out[27]: '11111111111'
In [28]: %timeit a.count(a[0]) == len(a)
The slowest run took 49.01 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 243 ns per loop
In [29]: %timeit len({}.fromkeys(a)) == len(a)
The slowest run took 38.81 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 645 ns per loop
In [30]: %timeit len(set(a)) == 1
The slowest run took 7.41 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 933 ns per loop
上述为检测11位手机号是否全部为同样的数字的判断
同样可以导入timeit包来执行
a = '11111111111'
def func_fromkeys():
print len({}.fromkeys(a)) == len(a)
def func_count():
print a.count(a[0]) == len(a)
import timeit
print timeit.Timer(func_count).repeat(10,1000000)
print timeit.Timer(func_fromkeys).repeat(10,1000000)