Code optimization cycle test

Remember, it is necessary to develop good habits from the beginning of the code.
The time complexity to measure the efficiency of the algorithm, while the loop more directly reflects the effectiveness of the procedure.

Qi cited high teacher to teach:

  1. Internal circulating minimize unnecessary calculation
  2. Nested loop, the inner loop is calculated to minimize, as much as possible put out.
  3. Local variables queries faster, try to use local variables

Here we use a different piece of code to test run at different times within a calculated amount of circulating situation:

#循环代码优化测试
import time
start = time.time()
for i in range(1000):
    result = []
    for m in range(10000):
        result.append(i*1000+m*100)
end = time.time()
print("耗时:{0}".format((end-start)))

start2 = time.time()
for i in range(1000):
    result = []
    c = i*1000
    for m in range(10000):
        result.append(c+m*100)
end2 = time.time()
print("耗时:{0}".format((end2-start2)))

Run results:
time: 2.6927947998046875
time: 2.1851699352264404

And when I put in the number of cycles to further increase the operating results for the 100000 is:
time: 27.680909395217896
time: 22.808008670806885
visible above the program to spend more than 21.4% of the time under the program.

Last stressed three times:

  1. Internal circulating minimize unnecessary calculation
  2. Nested loop, the inner loop is calculated to minimize, as much as possible put out.
  3. Local variables queries faster, try to use local variables
  4. Internal circulating minimize unnecessary calculation
  5. Nested loop, the inner loop is calculated to minimize, as much as possible put out.
  6. Local variables queries faster, try to use local variables
  7. Internal circulating minimize unnecessary calculation
  8. Nested loop, the inner loop is calculated to minimize, as much as possible put out.
  9. Local variables queries faster, try to use local variables
Released two original articles · won praise 0 · Views 9

Guess you like

Origin blog.csdn.net/qq_34351543/article/details/104267702