+ 1
A question about time complexity.
In python3, I have try the 2 codes below, and want to see which code runs faster. #code1 for i in range(10000): print(i) #code 2 print(0) print(1) print(2) [similar codes repeat 9995 more times here] print(9998) print(9999) I found out that "code 1" runs faster, but I don't know why. I think that both of the codes have time complexity arises from I/O time, but "code 1" includes iteration of i, which may be think like: print(i) i += 1 print(i) ... I adjust the execution time by time command in Unix shell. Does anyone know exactly why the first code runs faster? I think maybe due to code fetching time or something?
1 ответ
+ 5
It is possible that for languages which are interpreted, a slight, usually unnoticeable delay is present when the interpreter proceeds to interpreting the next line from the previous. In code 1, the interpreter interprets the 2 lines of code and immediately starts getting the job done. In code 2, the interpreter has to traverse 10000 lines of code and execute each statement independently before proceeding to the next line. This, however, pertains to the internal workings of the interpreter, which I am not familiar with. It is also possible that interpreting and executing range-based for loops are significantly optimized in Python.
However, I am fairly certain that it has nothing to do with time complexity.
I believe a different observation would be present in compiled languages. Your question is roughly this:
https://stackoverflow.com/questions/42735774/performance-single-loop-with-multiple-statements-or-multiple-loops-with-single
brought to the extreme.