Z
Z
zlodiak2019-02-20 21:29:57
Python
zlodiak, 2019-02-20 21:29:57

Why is the execution time different on different machines?

I tried to compare two algorithms that are looking for a unique element in a list. Further, to skip any checks, it is assumed that the list always contains more than 3 elements and the elements can only be 1 or 2.

#!/usr/bin/env python3

import timeit

def find_uniq_1(arr):
    ''' итоговая сложность: O(n) | время выполнения: 0.002494273998308927 '''
    a, b = set(arr) #O(len(arr))
    return a if arr.count(a) == 1 else b # O(n)

mock = [1 for x in range(100000)]
mock.extend([ 1, 1, 1, 2, 1, 1 ])
start = timeit.default_timer()
print(find_uniq_1(mock))
stop = timeit.default_timer()
print('Time for find_uniq_1: ', stop - start)  


def find_uniq_2(arr):
    ''' итоговая сложность: O(n) | время выполнения: 0.01582404098007828 '''
    first = arr[0]  # O(1)
    left = []       # O(1)
    right = []      # O(1)

    for n in arr:   # O(n)
        if n == first:
            left.append(n)      # O(1)
        else:
            right.append(n)     # O(1)

    return right[0] if len(left) > 1 else left[0]   # O(1)

mock = [1 for x in range(100000)]
mock.extend([ 1, 1, 1, 2, 1, 1 ])
start = timeit.default_timer()
print(find_uniq_2(mock))
stop = timeit.default_timer()
print('Time for find_uniq_2: ', stop - start)

As a result of measuring the execution time, it can be seen that the first algorithm is an order of magnitude faster. Is it normal for two algorithms with the same complexity to have execution times that differ by an order of magnitude?
I understand that a lot depends on the iron, but the order is a very specific indicator. And if the complexity in O-notation has such a large error, then is it necessary to bother with the complexity of the algorithm at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2019-02-20
@zlodiak

Once again, black and white. The complexity of the algorithm DOES NOT REFLECT real-time execution. Time can vary even a million times. Complexity REFLECTS the nature of the growth of time / memory with the growth of this your N.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question