After a lot of research, a lot of documentation of the add-on modules, and research in other Stackoverflows I got my answer.
In Estrutura de Dados
we do the Análise Assintótica de Algoritmos
, in case checked the best case O(1)
and other cases.
In fact this is the best way to observe the behavior of an algorithm and see how it behaves based on the number of comparisons it makes.
This is the human way of comparing algorithms.
There is now Estruturas de Dados
are or are close to O(1), the Hash
especially since it uses a single key instead of going through a whole list. Either it exists or it does not exist, there is no doubt.
In Python we have the Hash Structure based on two types: Dicionários e Conjuntos
Any query made in these structures will be O(1), and this makes the algorithm very fast.
In fact, the algorithm becomes so fast that its execution is not even in microseconds(I tested in code and this was confirmed).
Now the obstacles begin: Most Operating Systems can only guarantee maximum accuracy 1 second, has passed from that there is risk even of absurd values (the value of a time measured after being less than the value of the time measured before). The machine cannot express nanoseconds, which makes measuring fast algorithms impossible. The timing of an algorithm will depend on what is happening to the machine at that time.
So sadly, the best way to measure the algorithm’s running time is through asymptotic analysis.
Follow the code I tried on Nanoseconds.
from datetime import datetime
dt = datetime.now()
antes = dt.microsecond
def firstDuplicate(a):
dic={}
for x in a:
if(x in dic):
return x
dic[x]=1
return -1
firstDuplicate([1,2,2])
print(firstDuplicate([1,2,2,5,6,7,8,9,10,11,12,13,14,15,16,17]))
ps = datetime.now()
depois = ps.microsecond
print("Microsegundos:")
print(depois-antes)
I used a
profiler
to have (among other things) a measure of the time consumed by the program.import profile; profile.run("my_function()")
– Jefferson Quesado
From seconds to milliseconds, just divide by 1000. Not much secret.
– Woss