简体   繁体   中英

What would be the best way to store times of Algorithms

The program is to analyse different sorting algorithms on different cases. I want to store the algorithm name and with it i need to store 10 running time vales for case (a), then store separately 10 running values for case (b) Below is the code testing different sorting algorithms runtimes. My code loses the result after start of each algorithm as I dont know how to store them properly

def call(m):
    for i in range(m):
        makelist()

def makelist():
    lst=[10]
    for l in lst:
        testall(l)

def testall(n):
    flist = [insertionsort,selectionsort]
    if n < 1:
        n = 1
    testlist = [i for i in range(n)]
    lsr=[testlist.sort(),   testlist.sort(reverse=True),random.shuffle(testlist)]
    for f in flist:
        result=[]
        for g in lsr:
            copylist = copy.deepcopy(testlist)
            testfunction(copylist,f, result)

def testfunction(testlist, function,r):
    start_time = time.perf_counter()
    function(testlist)
    end_time = time.perf_counter()
    print('time =', (end_time - start_time), '; alg =', function.__name__, '(', len(testlist), ')')
    r.append(end_time - start_time)

Based on your outline, I'd suggest a defaultdict of list where the function name is the key and the various timings are appended to the value:

from collections import defaultdict

def testfunction(testlist, function, results):
    start_time = time.perf_counter()
    function(testlist)
    end_time = time.perf_counter()
    print('time =', (end_time - start_time), '; alg =', function.__name__, '(', len(testlist), ')')
    results[function.__name__].append(end_time - start_time)


results = defaultdict(list)

for f in flist:
    for g in lsr:
        copylist = copy.deepcopy(testlist)
        testfunction(copylist, f, results)

When you're finished, results will contain something like:

>>> results
defaultdict(<class 'list'>, {'haresort': [6.194799953483277, 1.947999534832776, 9.47999534832776, 4.799953483277619, 7.999534832776194, 6.194799953483277, 1.947999534832776, 9.47999534832776, 4.799953483277619, 7.999534832776194], 'snailsort': [8.327761947999534, 3.277619479995348, 2.776194799953483, 7.761947999534832, 7.619479995348327, 8.327761947999534, 3.277619479995348, 2.776194799953483, 7.761947999534832, 7.619479995348327]})

Just treat the defaultdict as an ordinary dictionary for the most part. For example, as the last thing you do in testall(), you can print out the contents of the results:

for function, timings in results.items():
    print(function, ":\n")
    print(*timings, sep="\n")
    print()

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