import time
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func()
end_time = time.time()
print(end_time - start_time)
return wrapper
# 方法1:+
@decorator
def method_1():
l = []
for i in range(1000000):
l += [i]
# 方法2:append
@decorator
def method_2():
l = []
for i in range(1000000):
l.append(i)
# 方法3:列表推导式
@decorator
def method_3():
l = [i for i in range(1000000)]
# 方法四:列表
@decorator
def method_4():
l = list(range(1000000))
method_1()
method_2()
method_3()
method_4()
结果:
0.11899971961975098
0.12200021743774414
0.08099985122680664
0.03900003433227539
效率:
多次运行发现,在生成特大数据量时,方法4>方法3>方法1/方法2。其中方法1和方法2效率相差无几,有时候方法1稍快,有时候方法2稍快。
网友评论