python simple algorithm optimization

  • Computer industry famous formula, proposed by the Swiss computer scientist Jack Nicklaus. Witts (Niklaus Wirth), also won the Turing Award 
    Program = algorithm + data structure
    not seen data structures and algorithms, sometimes face the problem may not have any idea I do not know how to start to solve;
    most of the time might solve the problem, but the program is not running efficiency and cost awareness, poor performance;
    sometimes help tool developed by others to solve the problem temporarily, but when it came to performance bottlenecks, and I do not know how to carry out targeted optimization * *
  • Simulation scenarios 
    a, b, c three number
    1. A + B + C = 1000 (0--1000)
    2.a ** ** 2 = B 2 + C 2 **
    find a, b, c possible combinations ? ? ?
  • normal

 

import time
s_time = time.time()
import datetime
starttime = datetime.datetime.now()
print(starttime)
for a in range(1,1001):
    for b in range(1,1001):
        for c in range(1, 1001):
            if a+b+c == 1000 and a**2 + b**2 == c**2:
                print("a= %s,b= %s,c= %s"% (a,b,c))
endtime = datetime.datetime.now()
yonghsi = the endtime - startTime
 Print ( " time is consumed:% S " % yonghsi)

 

    • time

  • Algorithm optimization
import time
starttime = time.time()
print(starttime)
for a in range(1,1001):
    for b in range(1,1001):
        c = 1000 - a - b
        if a**2 + b**2 == c**2:
            print("a= %s,b= %s,c= %s"% (a,b,c))
endtime = time.time()
print(endtime)
Yongshi = endtime- startTime
 Print ( " total time was:% S " % Yongshi)
  • timeit (python built-in test module)
Import the timeit    # Python built-in performance test module

def func():
    for a in range(1, 1001):
        for b in range(1, 1001):
            c = 1000 - a - b
            if a ** 2 + b ** 2 == c ** 2:
                print("a= %s,b= %s,c= %s" % (a, b, c))

timer01 = timeit.Timer ( " FUNC () " , " from __main__ Import FUNC " )
 # the Timer (first position you want to write performance test for which function. The second position from which to introduce this function) 
Print (timer01 .timeit (10) / 10)   # here timeit () represents the number of tests 1.2070892295 #

 
 
2020-01-07 00:08:26
 

Guess you like

Origin www.cnblogs.com/u-damowang1/p/12159151.html