Python 如何使此程序更快(更高效)?

Python 如何使此程序更快(更高效)?,python,Python,我有这个代码,它使用文件中每个单词的第一个字母创建唯一的密码。在创建每个密码(写入文件)之前,它会与文件中当前的所有密码进行比较,因此如果文件在写入另一个密码之前有50000个密码,则必须扫描所有50k密码。 用户可以输入所需的任意数量的密码,但数字越大,所需的时间越长,需要100k,这将花费很长时间。我如何对其进行优化以使程序运行得更快?密码生成不包括在代码中 for mainLoop in range(passnum): user = 0 newpass = ge

我有这个代码,它使用文件中每个单词的第一个字母创建唯一的密码。在创建每个密码(写入文件)之前,它会与文件中当前的所有密码进行比较,因此如果文件在写入另一个密码之前有50000个密码,则必须扫描所有50k密码。 用户可以输入所需的任意数量的密码,但数字越大,所需的时间越长,需要100k,这将花费很长时间。我如何对其进行优化以使程序运行得更快?密码生成不包括在代码中

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")
其他: new_passwords=set(line.strip()用于打开的行(“MnemPass.txt”)) 对于范围内的num(passnum): temp=generatePassword()

如果临时密码不在新密码中:
CurrentPasswords.add(临时)
其他:
“找到匹配项”
对于当前密码中的pw2:
storePass.write(pw2+“\n”)

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


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

您可以通过加载文件一次,然后将每个新密码附加到该文件中,而不是在循环中打开文件并逐行检查,从而大大减少运行时间,这里我在
generatePassword()中使用
uuid
生成长度在3到10之间的随机字符串

您的代码:

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
我稍微修改了它,以便在开始时加载文件,并为每个新密码追加密码,请注意,我们不再需要内部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

修改代码的配置文件:

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

如您所见,运行时间已从
45秒
减少到
27秒
!:)

注意:

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

我对10000个密码进行了测试,并删除了生成的文件以备下次使用:)

如果这是您认为可以改进的工作代码,它可能更适合。是的,它工作正常,我会这样做。运行时间可能取决于
generatePassword()的效率
方法是tooAFAIK,您只需将密码存储在文件中,并始终在每次迭代时读取和重写密码。只需要一个字典来存储密码,然后检查密码是否已经存在,这将是一个非常快速的操作,您可以在最后将字典内容保存到文件中。这应该比您现在所做的更有效率。@PruthviRaj该函数使用数组字典随机附加一个字母,它使用一个循环,然后将数组连接到字符串并返回结果。我不认为这会导致程序执行时间太慢。在保留一个集之前,您是指生成一组密码吗写入文件,然后检查?我仍然需要确保列表没有重复项。我知道循环中不断打开和关闭文件可能会减慢我将尝试限制的程序that@Doug_Brown他的意思是:
new_passwords=set();如果为True,则新密码.add(generatePassword())
set
s从不包含重复的密码,因此只要在有足够的元素时停止循环即可。这时:
对于新密码中的pw:outfile.write(pw)
或类似的东西。@Bakuriu和Cantfindname我使用了set,并使用set函数使其工作。它真的很快,我在外部打开了文件,执行时间大大减少了。我使用了set函数,并加快了程序的运行速度。无论如何,谢谢