Show the runtime of an algorithm in milliseconds in python?

Asked

Viewed 1,591 times

3

So far only found questions that show seconds. I would like to find in Milliseconds.

Follow the code I tried:

import time 
start = time.time()

def firstDuplicate(a):
    dic={}
    for x in a:
        if(x in dic):
            return x
        dic[x]=1
    return -1

firstDuplicate([1,2,2])


print("--- %s seconds ---" % (time.time() - start))
  • I used a profiler to have (among other things) a measure of the time consumed by the program. import profile; profile.run("my_function()")

  • From seconds to milliseconds, just divide by 1000. Not much secret.

2 answers

1

You can more accurately calculate the running time of a particular operation by sampling.

You repeat the same operation by N times and calculates the total time spent, with this, you are able to calculate the average time that the test operation takes to complete.

from datetime import datetime

# Quantidade de amostras
n = 1000000;

# Funcao em teste
def firstDuplicate(a):
    dic={}
    for x in a:
        if(x in dic):
            return x
        dic[x]=1
    return -1

# Registra o momento antes do teste
t0 = datetime.now()

# Repete a operacao em teste por N vezes...
for i in range( n ):

    # Operacoes em teste
    firstDuplicate([1,2,2])
    firstDuplicate([1,2,2,5,6,7,8,9,10,11,12,13,14,15,16,17])

# Registra o momento apos teste
t1 = datetime.now()

# Calcula o tempo de execucao das N operacoes executadas
diff = t1 - t0

# Calcula a media de tempo de execucao em milissegundos de cada operacao
med = (diff.total_seconds() * 1000) / n

# Exibe resultado do teste
print( "Tempo da operacao: " + str(med) + " ms" )

Exit:

Tempo da operacao: 0.002130244 ms

0

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.