2015-10-20 90 views
0

我有這個代碼,它使用文件中每個單詞的第一個字母創建唯一的密碼。在每個密碼創建(寫入文件)之前,它將與當前在文件中的所有密碼進行比較,因此如果文件具有在寫入另一個密碼之前需要50,000個密碼,它必須掃描所有50k。 用戶可以輸入任意數量的密碼,但數字越大需要花費的時間越長,需要很長時間我如何優化這個以使程序運行更快?口令產生不包括代碼如何讓這個程序更快(更高效)?

for mainLoop in range(passnum): 

     user = 0 
     newpass = generatePassword() # New password generated each iteration of loop 
     storePass = open("MnemPass.txt","a") 
     print ("PASSWORD GENERATED ") 

     #Checks if file is empty if True write first password 
     fileEmpty = os.stat("MnemPass.txt").st_size == 0 
     if fileEmpty == True: 
      storePass.write(newpass) 
      storePass.write("\n") 
      storePass.close() 
      print ("FIRST PASSWORD WRITTEN") 

     #IF file is not empty Read line by line and compare each with new password generated returns boolean value 
     elif fileEmpty == False: 
      storePass = open("MnemPass.txt","r") 
      with open("MnemPass.txt") as f: 
       fileData = f.read().splitlines() 
       linelength = len(fileData).__int__() 
       filemax = linelength 
       num = linelength #Number used to cycle through array set to size of list 
       #print(linelength+10) 

       for iterate in range(linelength): 
        num = num - 1 #Number decreases each pass 
        #print num 
        if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass 
         go = True 

        if fileData[num]==newpass: #changed 
         print ("match found: PASSWORD : "+fileData[num]) 
         passMatch = open("Matchpassword.txt","a") 
         passMatch.write(newpass) 
         passMatch.write("\n") 
         passMatch.close() 
         go = False 
         break 

        #places new password once it does not match and all elements prev passwords are compared 
        if go == True and num == 0: 
         storePass = open("MnemPass.txt","a") 
         storePass.write(newpass) 
         storePass.write("\n") 
         storePass.close() 
         print ("NEW WRITTEN") 



      if linelength == filemax: 

       num = num -1 

*新的代碼 - 我使用的設定功能*

 passnum = (input("How many passwords do you need :")) 
    sTime = datetime.now()

storePass = open ("MnemPass.txt","a") # file open out of loop to increase speed fileEmpty = os.stat("MnemPass.txt").st_size == 0

new_passwords = set() CurrentPasswords = set()

if fileEmpty == True: while len(new_passwords)!= passnum: #will cause problems if dictionary cannot create amount needed new_passwords.add(generatePassword())

for pw in new_passwords: 
     storePass.write(pw + "\n") 

其他:開放(「MnemPass.txt線路 new_passwords =集(line.strip() 「)) 有效範圍內的NUM(passnum): 溫度= generatePassword()

if temp not in new_passwords: CurrentPasswords.add(temp) else: "match found"

爲PW2在CurrentPasswords: storePass.write(對W2 +「\ n」)

+1

如果這是**工作代碼**,你認爲可以改進,它可能更適合[codereview.se]。 – jonrsharpe

+0

高雅其工作確定生病做 –

+0

運行時間可能取決於你的'generatePassword()'方法是如何有效的太 –

回答

0

在,你在這裏提出您的代碼在循環運行的情況: 檢查在每次循環迭代整個文件是不是很有效。 保存一組創建的密碼並在添加新密碼之前檢查新密碼是否已經存在,會更有效率。 同樣在這種情況下,您應該只在主for循環外打開一次文件,然後關閉它。

如果您的程序只添加一個密碼然後返回,最好以您的文件保持排序的方式添加每個新密碼。這樣,您可以使用二進制搜索來搜索密碼是否已經存在。

+0

保持一個集合是否意味着在寫入文件之前生成一組密碼然後檢查?我仍然需要確保列表沒有重複。我知道循環內文件的不斷打開和關閉可能會減慢程序的運行速度,我會盡力限制這個值 –

+0

@Doug_Brown他的意思是:'new_passwords = set();而True:new_passwords.add(generatePassword())''set'從不包含重複項,所以當你有足夠的元素時你只需要停止循環。在這一點上:'在new_passwords中爲pw:outfile.write(pw)'或類似的東西。 – Bakuriu

+0

好吧,感謝所有的幫助傢伙 –

1

你可以通過加載文件一次,然後附加每個新的密碼,而不是循環打開文件並逐行檢查,從而大大減少運行時間,這裏我使用uuidgeneratePassword()產生一個長度在3和10

您的代碼:

def func(passnum): 
    import os,uuid,random 
    def generatePassword(): 
     return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)] 
    for mainLoop in range(passnum): 

      user = 0 
      newpass = generatePassword() # New password generated each iteration of loop 
      storePass = open("MnemPass.txt","a") 
      print ("PASSWORD GENERATED ") 

      #Checks if file is empty if True write first password 
      fileEmpty = os.stat("MnemPass.txt").st_size == 0 
      if fileEmpty == True: 
       storePass.write(newpass) 
       storePass.write("\n") 
       storePass.close() 
       print ("FIRST PASSWORD WRITTEN") 

      #IF file is not empty Read line by line and compare each with new password generated returns boolean value 
      elif fileEmpty == False: 
       storePass = open("MnemPass.txt","r") 
       with open("MnemPass.txt") as f: 
        fileData = f.read().splitlines() 
        linelength = len(fileData).__int__() 
        filemax = linelength 
        num = linelength #Number used to cycle through array set to size of list 
        #print(linelength+10) 

        for iterate in range(linelength): 
         num = num - 1 #Number decreases each pass 
         #print num 
         if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass 
          go = True 

         if fileData[num]==newpass: #changed 
          print ("match found: PASSWORD : "+fileData[num]) 
          passMatch = open("Matchpassword.txt","a") 
          passMatch.write(newpass) 
          passMatch.write("\n") 
          passMatch.close() 
          go = False 
          break 

         #places new password once it does not match and all elements prev passwords are compared 
         if go == True and num == 0: 
          storePass = open("MnemPass.txt","a") 
          storePass.write(newpass) 
          storePass.write("\n") 
          storePass.close() 
          print ("NEW WRITTEN") 



       if linelength == filemax: 

        num = num -1 

我稍微修改它加載該文件在啓動本身並追加爲每一個新的密碼,我們並不需要爲內部循環不再另行通知,代碼變成:

def func2(passnum): 
    import uuid 
    import os, random 
    linelength = 0 
    fileData = [] 
    if os.path.isfile('MnemPass.txt'): 
     f = open("MnemPass.txt", "r") 
     fileData += f.read().splitlines() 
     linelength = len(fileData).__int__() 
     f.close() 

    def generatePassword(): 
     return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)] 

    for mainLoop in range(passnum): 

     user = 0 
     newpass = generatePassword() # New password generated each iteration of loop 
     storePass = open("MnemPass.txt", "a") 
     print ("PASSWORD GENERATED ") 

     # Checks if file is empty if True write first password 
     fileEmpty = os.stat("MnemPass.txt").st_size == 0 
     if fileEmpty == True: 
      storePass.write(newpass) 
      storePass.write("\n") 
      storePass.close() 
      print ("FIRST PASSWORD WRITTEN") 

     # IF file is not empty Read line by line and compare each with new password generated returns boolean value 
     elif fileEmpty == False: 
      storePass = open("MnemPass.txt", "r") 
      filemax = linelength 
      num = linelength # Number used to cycle through array set to size of list 
      # print(linelength+10) 

      if newpass in fileData: 
        print ("match found: PASSWORD : " , fileData.index(newpass)) 
        passMatch = open("Matchpassword.txt", "a") 
        passMatch.write(newpass) 
        passMatch.write("\n") 
        passMatch.close() 
      else: 
        linelength += 1 
        fileData.append(newpass) 
        storePass = open("MnemPass.txt", "a") 
        storePass.write(newpass) 
        storePass.write("\n") 
        storePass.close() 
        print ("NEW WRITTEN") 
      if linelength == filemax: 
       num = num - 1 

個人資料代碼:

enter image description here

個人資料修改後的代碼:

enter image description here

正如你所看到的運行時間已經從45secs減少到27secs!:)

注:

我跑了10000個密碼測試並刪除生成的文件的下一次:)

+0

不錯感謝您的幫助 –

+0

@Doug_Brown,歡迎您:) –

+0

我使用的設定功能,加快了項目一噸的感謝反正 –