简体   繁体   中英

Calculate run time of a given function python

I have created a function that takes in a another function as parameter and calculates the run time of that particular function. but when i run it, i can not seem to understand why this is not working . Does any one know why ?

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)

run time screen shot在此处输入图片说明

It looks like the code just executes incredibly fast. In bubbleSort , I added an additional for loop to execute the comparisons another 10000 times:

@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

Now the result is:

 ('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)

etc... @vishes_shell points this out in the comments as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM