计算给定函数python的运行时间

时间:2016-09-23 16:35:46

标签: python timeit

我创建了一个函数,它接受另一个函数作为参数,并计算该特定函数的运行时间。但是当我运行它时,我似乎无法理解为什么这不起作用。有人知道为什么吗?

import time
import random
import timeit
import functools

def ListGenerator(rangeStart,rangeEnd,lenth):
 sampleList = random.sample(range(rangeStart,rangeEnd),lenth)
 return sampleList


def timeit(func):
    @functools.wraps(func)
    def newfunc(*args):
        startTime = time.time()
        func(*args)
        elapsedTime = time.time() - startTime
        print('function [{}] finished in {} ms'.format(
            func.__name__, int(elapsedTime * 1000)))
    return newfunc

@timeit
def bubbleSort(NumList):
    compCount,copyCount= 0,0

    for currentRange in range(len(NumList)-1,0,-1):
        for i in range(currentRange):
            compCount += 1
            if NumList[i] > NumList[i+1]:
                temp = NumList[i]
                NumList[i] = NumList[i+1]
                NumList[i+1] = temp
   # print("Number of comparisons:",compCount)



NumList = ListGenerator(1,200,10)
print("Before running through soriting algorithm\n",NumList)
print("\nAfter running through soriting algorithm")
bubbleSort(NumList)
print(NumList,"\n")
for i in range (0, 10, ++1):
 print("\n>Test run:",i+1)
 bubbleSort(NumList)
 compCount = ((len(NumList))*((len(NumList))-1))/2
 print("Number of comparisons:",compCount)

运行时屏幕截图 enter image description here

1 个答案:

答案 0 :(得分:0)

看起来代码执行速度非常快。在bubbleSort中,我添加了一个额外的for循环来执行另一个10000次的比较:

@timeit
def bubbleSort(NumList):
    compCount,copyCount= 0,0

    for i in range(10000):
        for currentRange in range(len(NumList)-1,0,-1):
            for i in range(currentRange):
                compCount += 1
                if NumList[i] > NumList[i+1]:
                    temp = NumList[i]
                    NumList[i] = NumList[i+1]
                    NumList[i+1] = temp

现在的结果是:

 ('Before running through soriting algorithm\n', [30, 18, 144, 28, 155, 183, 50, 101, 156, 26])

After running through soriting algorithm
function [bubbleSort] finished in 12 ms
([18, 26, 28, 30, 50, 101, 144, 155, 156, 183], '\n')
('\n>Test run:', 1)
function [bubbleSort] finished in 12 ms
('Number of comparisons:', 45)
('\n>Test run:', 2)
function [bubbleSort] finished in 8 ms
('Number of comparisons:', 45)
('\n>Test run:', 3)

等... @vishes_shell也在评论中指出了这一点。