Show the runtime of an Algorithm in milliseconds in python?

Question:

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

Here's 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))

Answer:

You can more accurately calculate the execution time of a given operation by sampling.

You repeat the same operation N times and calculate the total time taken, with this you are able to calculate the average time that the operation under test 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
Scroll to Top
AllEscort