亲宝软件园·资讯

展开

python使用timeit python使用timeit时间模块

JSon liu 人气:0
想了解python使用timeit时间模块的相关内容吗,JSon liu在本文为您仔细讲解python使用timeit的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,timeit,时间,下面大家一起来学习吧。

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))

加载全部内容

相关教程
猜你喜欢
用户评论