+ 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.
7 Answers
+ 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.
+ 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? đ€
+ 2
Sergey Ushakov its only for experiment not a programme.
+ 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
:)
+ 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^^
+ 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
- 1
for(1 = 1) {}