为什么python处理排序的列表比处理未排序的列表花费更多的时间

2024-03-28 10:47:16 发布

您现在位置:Python中文网/ 问答频道 /正文

示例:

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 test.py:716(foo)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

0.143秒内3次函数调用

订货人:标准名称

   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 test.py:716(foo)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}




Tags: runin名称for标准foorandomcprofile
1条回答
网友
1楼 · 发布于 2024-03-28 10:47:16

还没有真正的答案,但是评论的范围太小了。你知道吗

由于random.shuffle()会产生相同的结果,我决定实现自己的shuffle函数,并改变洗牌的次数。(在下面的示例中,它是xrange300000的参数。你知道吗

def my_shuffle(array):
    for _ in xrange(300000):
        rand1 = random.randint(0, 999999)
        rand2 = random.randint(0, 999999)
        array[rand1], array[rand2] = array[rand2], array[rand1]

另一个代码几乎没有修改:

import cProfile, random, copy
def foo(lIn): return [i*i for i in lIn]
lIn = [random.random()*100000 for i in range(1000000)]
lIn1 = copy.copy(lIn)
my_shuffle(lIn1)
cProfile.run('foo(lIn)')
cProfile.run('foo(lIn1)')

第二次cProfile的结果取决于我洗牌的次数:

10000 0.062个
100000 0.082
200000 0.099
400000 0.122
800000 0.137
8000000 0.141
10000000 0.141
1亿0.248

看起来数组越乱,在某一点上的操作时间就越长。(我不知道最后的结果。花了很长时间,我在后台做了一些浅色的其他东西,我真的不想再试。)

相关问题 更多 >