当前位置:主页 > 软件编程 > Python代码 >

python使用timeit时间模块

时间:2022-05-24 09:36:19 | 栏目:Python代码 | 点击:

1. timeit.timeit(stmt=‘pass', setup=‘pass', timer=<default timer>, number=default_number)

2. timeit.repeat(stmt="pass", setup="pass", timer=default_timer, repeat=default_repeat, number=default_number)

3. class timeit.Timer(stmt=‘pass', setup=‘pass', timer=<timer function>)

import timeit
def t1():
 li = [i for i in range(100000)]
def t2():
 li = []
 for i in range(100000):
  li += [i]
def t3():
 li = []
 for i in range(100000):
  li.append(i)
def t4():
 li = []
 list(range(100000))
def t5():
 li = []
 for i in range(100000):
  li.extend([i])
def t6():
 li = []
 for i in range(100000):
  li.insert(0,i)

# 方式1:timeit.timeit()
# list_t1 = timeit.timeit('t1()','from __main__ import t1',number=1)
# print("i for i in range(100000): %s" %(list_t1))

# 方式2:timeit.repeat()
# list_t2 = timeit.repeat('t2()','from __main__ import t2',repeat=1,number=1)
# print("li += i: %s" %(str(list_t2)))

# 方式3:timeit.Timer
# timer3 = timeit.Timer('t3()','from __main__ import t3')
# print("li.append(i): %s" %(timer3.timeit(number=1)))

# 直接传入字符串对象
# list_l4 = timeit.timeit('li = [i for i in range(1000)]',number=1)
# print(str(list_l4))

# 传入多个函数对象(;或空行分隔)
list_l5 = timeit.repeat('t4();t5();t6()','from __main__ import t4;from __main__ import t5;from __main__ import t6',repeat=1,number=1)
print(str(list_l5))

您可能感兴趣的文章:

相关文章