# Comparing the computational time of two ways of the same result

The two following codes accomplish the same task

1)

L=list(range(0,100,10))
Ld0=[x^2 for x in L]
Lc=[]
a=0
for i in range(len(Ld0)):
if (Ld0[i]%6 == 0) & (Ld0[i]<= 3200) :
Lc.append(Ld0[i])
a+=1


2)

L=list(range(0,100,10))
Ld0=[x^2 for x in L]
Ld2=[x for x in Ld0 if (x%6 == 0) & (x<= 3200)]


which can be shown by Lc==ld2.

If I can fin easily the cpu computation time in adding %time to the first, this is not the case for the second. How to see which way is the fastest ?

edit retag close merge delete

On peut virer le list dans la première ligne. et utiliser un itérateur dans la deuxième.

( 2023-02-18 09:27:28 +0200 )edit

If there is no obvious winner, you can run the two algorithms in parallel, and stop computation as soon as one produces the result - see https://ask.sagemath.org/question/59480/

( 2023-02-18 14:16:04 +0200 )edit

Sort by » oldest newest most voted

Well... the %time and %%time magics can be used to display the execution time of an instruction or a cell. See %time. A controlled-precision version s available through the function timeit.

If you want to use this time of execution, you have to time it yourself. One possibility :

def A1(l, s=1): # First algorithm, defined as a function for laziness' sake
L=list(range(0,l,s))
Ld0=[x^2 for x in L]
Lc=[]
a=0
for i in range(len(Ld0)):
if (Ld0[i]%6 == 0) & (Ld0[i]<= 3200) :
Lc.append(Ld0[i])
a+=1
return Lc
def A2(l, s=1): # Second algorithm (ditto...)
L=list(range(0,100,10))
Ld0=[x^2 for x in L]
Ld2=[x for x in Ld0 if (x%6 == 0) & (x<= 3200)]
return Ld2
from time import time as stime # See Python documentation
t0 = stime()
R1 = A1(100, 10)
t1 = stime()
R2 = A2(100, 10)
t2 = stime()
Res = [(R1, t1-t0), (R2, t2-t1)] # Wrap results with execution time


which allows you to see that the first version is

sage: Res[0][1]/Res[1][1]
6.241007194244604


about 6 times slower than the second.

HTH,

more

Thanks Emmanuel. Should I say that a the second method is always more efficient that the first, that is working directly inside a list is better than to construct a loop (I know that list comprehension is recursive and has been optimized)?

( 2023-02-18 12:54:10 +0200 )edit

In the definition of A2, the second line should be probably L=range(0,l,s) ?

( 2023-02-18 14:01:56 +0200 )edit

If you will be iterating, using ‘range(…)’ is faster than ‘list(range(…))’. Only convert to a list if you really need all of the elements at once.

( 2023-02-19 03:12:32 +0200 )edit