Execution time of the code

Asked

Viewed 34 times

-1

Good evening, what could I do to know the time of each iteration that my code makes? Searching a little I found the command time.time(), but when the use in my code I get only 0.0 results. Someone could help me?

Follow the implementation of my code:

x_values = []
def eq_diff3(V):
    return -V/10
values_dt = [0.01,0.1,1,2,10]
T = 50
for dt in values_dt:
    start = time.time() #Começa contando aqui
    V0 = 50
    t = np.linspace(0,T,int(T/dt)+1)
    x = np.zeros(len(t))
    x[0] = V0    
    for i in range(1,len(t)):
        start = time.time()        
        x[i] = x[i-1] + eq_diff3(x[i-1])*dt    
    vm_all.append(x)
    x_values.append(t)
    end = time.time() # termina de contar aqui
    duration = end - start 
    print(duration) #printa quanto tempo demorou

Exit:

0.0
0.0
0.0
0.0
0.0
  • 1

    Try to be really small: https://ideone.com/vCU99h. Check what are the values of start and end individually.

  • Thank you, I modified the code to first print the star value and then the end value as you suggested. I got the following for the first loop: start value is: 1599744343.5452778 end value is: 400.4330963 What this means?

  • The website you sent me is telling me the time of each loop?

1 answer

1


Use the timeit, he is more precise than the time for fast code snippet.

import timeit

tempo_inicial = timeit.default_timer()

print('Olá Mundo!')

tempo_final = timeit.default_timer()

print('Tempo Total:', tempo_final - tempo_inicial)

Also, inside your for loop has a line start = time.time(), I think you need to remove that line.

  • Hi, thanks for the answer. I modified the code above and got the following outputs -1599743943.112952 -1599743943.1129992 -1599743943.1123936 -1599743943.1121457 -1599743943.1130106 What do I need to see are the numbers after the decimals? What is the time unit of it? Thank you.

  • 1

    Strange that gave negative numbers, should give a result similar to "Total Time: 0.00013969999999955" in seconds. Inside your for loop has a line "start = time.time()", I think you need to remove this line.

  • Ah, nice. It was my own mistake. Now I got the values: 0.006424300000162475; 0.0015780999999606138; 0.00027569999997467676; 0.00019210000004932226; 0.00013030000013714016;

  • I’m glad it worked out, I edited the answer.

Browser other questions tagged

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