sum list is faster or fomula?! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

sum list is faster or fomula?!

i got diffrenet results with change x value sometimes formula is faster or sum list in loop! https://code.sololearn.com/cqFuj68UGhNn/?ref=app

22nd Apr 2022, 1:51 PM
mohammed shibli
mohammed shibli - avatar
4 Answers
+ 3
mohammed shibli , to get something like reliable values for the execution time of doing a summation, the code should be modify: x = 11 # this is to less steps that has to be done. in this case we get a very wide spread of resulting time. should be at least 1_000_000 print(ad[0]) st1 = time.process_time_ns() # the measure unit is to small, so we get large numbers to compare for i in range(1, x+1): res1 = (i*(i+1)//2) #txt1 = f'({i} * ({i} + 1) // 2)' # remove everything that is not directly related to the summation process #print(res1, txt1) # remove everything that is not directly related to the summation process
22nd Apr 2022, 2:12 PM
Lothar
Lothar - avatar
+ 3
mohammed shibli , in the file you can find a sample of how it can be done. https://code.sololearn.com/ccJ0KSEihfzM/?ref=app
22nd Apr 2022, 2:43 PM
Lothar
Lothar - avatar
+ 3
Also consider effects of warming up the interpreter and just in time compilation. Using a huge number of tests will help, but a warm-up phase should be used before starting any measurements. And if you want to interpret the results, include a five stats evaluation (min, max, median, and 1/4 and 3/4 quantils), and the average and standard deviation.
22nd Apr 2022, 3:13 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
thank you Lothar for pointing it out, i try to update it but you nealed it faster. for time func that's correct timeit is better than process_time_ns and using many prints just to clear my point is this faster >>> (11*(11+1)//2) or this one: >>> sum([x for x in range(11+1)])
22nd Apr 2022, 3:14 PM
mohammed shibli
mohammed shibli - avatar