如何让这个程序更快(更高效)?

时间:2015-10-20 15:25:15

标签: python

我有这个代码,使用文件中每个单词的第一个字母创建唯一的密码。在创建每个密码(写入文件)之前,它将与当前文件中的所有密码进行比较,因此,如果文件在另一个写入之前有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

*新代码 - 我使用了set函数*

 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")

else: new_passwords = set(line.strip() for line in open ("MnemPass.txt")) for num in range(passnum): temp = generatePassword()

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

for CurrentPasswords中的pw2:            storePass.write(pw2 +" \ n")

2 个答案:

答案 0 :(得分:1)

您可以通过加载文件一次然后将每个新密码附加到其中而不是逐个打开文件并逐行检查来大大减少运行时间,我在uuid中使用generatePassword()来生成一个长度在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

我略微修改它以在启动时加载文件并附加每个新密码,注意我们不再需要内部for循环,代码变为:

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个密码的测试并删除了生成的文件以供下次传递:)

答案 1 :(得分:0)

如果你的代码在循环中运行,就像你在这里一样: 在每次循环迭代中检查整个文件效率不高。 保留一组创建的密码并在添加之前检查集合中是否已有新密码更有效。 同样在这种情况下,您应该只在main for循环外打开一次文件,然后关闭它。

如果您的程序只添加一个密码然后返回,则最好以文件保持排序的方式添加每个新密码。这样,您可以使用二进制搜索来搜索密码是否已存在。