【发布时间】:2015-07-19 22:44:03
【问题描述】:
玩一下python profiler,看下面的代码:
>>> def testa():
... a = []
... pr = cProfile.Profile()
... pr.enable()
... for i in range(100000):
... a.append(1)
... pr.disable()
... pr.print_stats()
>>> def testb():
... a = []
... pr = cProfile.Profile()
... pr.enable()
... for i in range(100000):
... a = a + [1]
... pr.disable()
... pr.print_stats()
基本上我想看看append 方法与自连接列表之间的结果,我认为自连接会更昂贵,而当我调用testb 时,它实际上需要更长的时间才能完成。
但是分析器的结果是错误的?
>>> testa()
100002 function calls in 0.006 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
100000 0.005 0.000 0.005 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.001 0.001 0.001 0.001 {range}
>>> testb()
2 function calls in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.001 0.001 0.001 0.001 {range}
【问题讨论】:
-
使用
timeit,你会看到很大的不同,a=[];for i in range(100000);a = a + [1] -> 22s,a=[];for i in range(100000);a.append(1) -> 7.84ms。