【发布时间】:2018-08-30 04:37:37
【问题描述】:
例子:
import cProfile, random, copy
def foo(lIn): return [i*i for i in lIn]
lIn = [random.random() for i in range(1000000)]
lIn1 = copy.copy(lIn)
lIn2 = sorted(lIn1)
cProfile.run('foo(lIn)')
cProfile.run('foo(lIn2)')
结果:
0.075 秒内调用 3 个函数
排序者:标准名称
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.005 0.005 0.075 0.075 :1() 1 0.070 0.070 0.070 0.070 测试.py:716(foo) 1 0.000 0.000 0.000 0.000 {方法'禁用''_lsprof.Profiler'对象}3 个函数调用在 0.143 秒内
排序者:标准名称
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.006 0.006 0.143 0.143 :1() 1 0.137 0.137 0.137 0.137 测试.py:716(foo) 1 0.000 0.000 0.000 0.000 {方法'禁用''_lsprof.Profiler'对象}【问题讨论】:
-
这没有意义
-
它似乎与排序没有任何关系。你可以用
random.shuffle(lIn1)代替 sort 和cProfile.run('foo(lIn1)'),你会得到同样的结果。 -
是什么导致处理时间加倍?
-
也许第一个列表还在缓存中?而且您在第一次测试调用中使用的是
lIn,而不是lIn1。
标签: python