+ 2

How to make for loop fast?

for i in range(100000000000): continue print('hi') #after 1 min hi is printed means for loop take 1 min for his full execution here any idea that i can run this for loop in less than 1 sec.

28th Sep 2018, 3:31 AM
Maninder $ingh
Maninder $ingh - avatar
7 ответов
+ 3
Your loop does nothing. You can speed up your program by removing the loop. It is what performance optimization does: removing parts of program, that spends a lot of computer resources to useless things.
28th Sep 2018, 3:51 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 2
You can take the start time and use the loop to check if 950 ms have passed. If so, you can break the loop and 'hi' will be printed in just under 1 second. Why though? 🤓
28th Sep 2018, 6:59 AM
Anna
Anna - avatar
+ 2
Sergey Ushakov its only for experiment not a programme.
28th Sep 2018, 10:27 AM
Maninder $ingh
Maninder $ingh - avatar
+ 2
when i started coding with basic for zx spectrum i wrote a program that was doing a word lookup in the array. as i had no idea about hashing i just used a for loop to check that the word exists in tge array. the program was really slow , i tried to make it better and dicsovered that i can write the logic in the machine code, so i learnt Assembler language by accident and chanfed my code to use assembler command to search for a string in memory - the program worked 10 times faster. that was amazing. my point here is very hard to achieve a good speed using for loop in the language like python, try c or c ++ or assemblet to get the speed. i have seen several job offers about rewriting an algorithm from python into c++. why? because the program was slow. also there are specialized libraries written in python optimized for speed. they are fast enough for specific tasks only Challenge yourself to learn assembler and your life will never be the same :)
28th Sep 2018, 7:18 PM
wave rider
+ 1
- set i to (almost) end of range before continue - get a faster machine - see comments above - maybe use xrange for small speedup (?, only Python 2.x) - ... Otherwise you can't just magically make the loop faster^^
28th Sep 2018, 7:21 AM
Matthias
Matthias - avatar
+ 1
I coded in sololearn playground with 10**10 https://code.sololearn.com/csQiUPhlRkVG/?ref=app The result is: Time Limit Exceed 😓😓😓😓😓😓😓 For a for loop in python, seems that it prepares for all the number of time first, and then carry out one by one. So it takes time to prepare each execution, even though the execution is empty. #Unlike human brain, if you put your code in Python Challenge, challengers will immediately knows that the for loop do nothing and types the output is hi
28th Sep 2018, 10:38 AM
Gordon
Gordon - avatar
- 1
for(1 = 1) {}
30th Sep 2018, 3:05 PM
callum willcocks
callum willcocks - avatar