小编lui*_*ipe的帖子

为什么我的排序代码的执行时间不一致?

我正在学习python,我已经实现了一个快速排序算法(种类).我知道python的sort()方法会更快,但我想知道多少,所以我用timeit模块进行比较.

我为该sort()方法创建了一个"包装器"函数,因此它使用与我的实现相同的语法(并停止进行就地排序)并调用timeit.repeat(3, 2000)这两个函数.

以下是我的功能结果:

[0.00019502639770507812, 0.00037097930908203125, 0.00013303756713867188]
Run Code Online (Sandbox Code Playgroud)

而对于python的sort():

[0.0001671314239501953, 0.0001678466796875, 0.00016808509826660156]
Run Code Online (Sandbox Code Playgroud)

如您所见,python的算法执行时间比我自己的执行时间更加一致.有谁知道为什么?

码:

import timeit
import random


def quick(lst):
    if not lst:
        return []
    else:
        first, rest = lst[0], lst[1:]
        great = []
        less = []
        for item in rest:
            great.append(item) if item >= first else less.append(item)
        return quick(less) + [first] + quick(great)

def sort(lst):
    lst.sort()
    return lst


x = [random.randint(1, 10000) for i in xrange(1, 1000)]

quick_t = timeit.Timer("'quick(x)'")

print quick_t.repeat(3, …
Run Code Online (Sandbox Code Playgroud)

python sorting performance time

3
推荐指数
1
解决办法
106
查看次数

标签 统计

performance ×1

python ×1

sorting ×1

time ×1