timeit:Python标准库中自带的模块,是一个用来测试代码执行时间的模块。
class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
timeit.Timer.timeit(number=1000000)
Timer是测量小段代码执行速度的类,stmt参数是要测试的代码语句(statment),setup参数是运行代码时需要的设置,timer参数是一个定时器函数,与平台有关。
timeit: Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。
下面是timeit的示例
from timeit import Timer
def solution1():
A= [4,3,4,4,4,2]
# write your code in Python 3.6
len_A = len(A)
size = 0
leader = -1
index = -2
result = 0
count_left = 0
for i in A:
if size ==0:
leader = i
size +=1
index +=1
else:
if leader ==i:
size +=1
else:
size-=1
leader_count = len([i for i in A if i == leader]) # count
if leader_count <= len_A//2:
return 0
for i in range(len_A):
if A[i] == leader:
count_left +=1
if count_left>(i+1)//2 and leader_count-count_left>(len_A-i-1)//2:
result +=1
return result
t1 = Timer("solution1()","from __main__ import solution1")
print("my solution",t1.timeit(number=1000), "seconds")
结果
my solution 0.004183967000244593 seconds