from time import time
def timeit(func):
'''Use this decorator to measure execution time of a function.
eg.
@timeit
def yourFunction(args):
dosomething...
'''
def wrapper(*args, **kwargs):
start = time()
res = func(*args, **kwargs)
elapsed = time() - start
print('Function %s costs time: %10.6f seconds.' % (func.__name__, elapsed))
return res
return wrapper
# 4 different ways to generating a list of n numbers starting with 0
# Using concatenation
@timeit
def gen_list_1(n):
L = []
for i in range(n):
L = L + [i]
# Using append method
@timeit
def gen_list_2(n):
L = []
for i in range(n):
L.append(i)
# Using list comprehension
@timeit
def gen_list_3(n):
L = [i for i in range(n)]
# Using list construction
@timeit
def gen_list_4(n):
L = list(range(n))
if __name__ == '__main__':
gen_list_1(100000)
gen_list_2(100000)
gen_list_3(100000)
gen_list_4(100000)
The result as below:
Function gen_list_1 costs time: 19.48219490 seconds.
Function gen_list_2 costs time: 0.01999998 seconds.
Function gen_list_3 costs time: 0.00999999 seconds.
Function gen_list_4 costs time: 0.00999999 seconds.
5932

被折叠的 条评论
为什么被折叠?



