2

I've tried to count the done operations in a algorithm the following way

def selection_sort(arr):
    ops = 0  # The number of done operations
    for i in range(0, len(arr)):
        ops += 1
        least_idx = i
        ops += 1
        for j in range(i, len(arr)):
            ops += 1
            if arr[j] < arr[least_idx]:
                ops += 1
                least_idx = j
                ops += 1
        arr[i], arr[least_idx] = arr[least_idx], arr[i]
        ops += 3
    return ops

Is it correct? And if it is, how to do it for a recursive algorithm like merge sort? And as for the runtime, I'm afraid that caching of the previous results will impact the next ones. The testing process is the following:

from random import sample

sort_algos = [selection_sort, insertion_sort, merge_sort]
for algo in sort_algos:
    for n in range(7, 8):
        arr = sample(range(0, 2**n), 2**n)
        algo(arr)

And in the end I want to have measures of the results for each n. Thank you in advance.

john
  • 23
  • 2
  • 1
    You first need to figure out what an "operation" that takes time is. – Alex Mandelias Sep 27 '20 at 09:29
  • Measuring the number of "operations" is too vague to actually be useful. What you might want it to mean is the number of python lines executed, the number of opcodes, the number of cpu instructions excuted. Usually, none of those matter. What matters is the time it takes. – Gaëtan de Menten Sep 27 '20 at 09:37
  • @AAAlex123 I measure done operations and runtime of the function separately. The measurement of the number of the operations is just simple determination of the asymptotic complexity of the algorithm – john Sep 27 '20 at 09:38
  • All algorithms should work with the same sample array to be comparable. And if you want to count something, just count loop iterations. – Wups Sep 27 '20 at 09:48
  • Does this answer your question? [How can you profile a Python script?](https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script) – woblob Sep 27 '20 at 09:50
  • @john I should've been more clear: which statements actually count as taking time. For example, for a sorting algorithm a comparison is what takes time `ls[i] < ls[j]` not actually getting the items `ls[i]`. In this sense, figure out which of the actions your algorithm performs actually impacts performance – Alex Mandelias Sep 27 '20 at 14:49

0 Answers0