如何提高我的python脚本的速度?

时间:2016-07-03 20:08:45

标签: python python-2.7

我写了这个非常好的python代码,它将遍历一个完整的名称或单词和内容列表,然后过滤一些东西,然后保存它们,但随后 我有一个很大的问题,就是速度,我试图通过做某事来解决这个问题,但它没有任何不同。那么有没有办法提高这个程序的速度?

#!/usr/bin/env python 2.7.12
#
#
#
from os import system
from time import sleep
from os  import path
from sys  import exit


def Main():
    global wordlist,Name
    system('clear')
    wordlist = raw_input("Enter The listfile Name: ")  
    if not path.exists(wordlist):
        system('clear');exit('\'%s\' Not Found' %wordlist)

    system('clear');Name = raw_input("Enter Name To Save As: ") 
    if path.exists(Name):
        system('clear');exit('\'%s\' Already Exists' %Name)



def Generate(lst,save):
    words = open(lst,'r')
    Wordlist = open(save,'a')
    Bank=[]
    for word in words:
        if int(len(str(word))-1) > 7 and int(len(str(word))-1) <= 10 and str(word).lower() not in Bank:
            system('clear')
            print '[+] Modding: %s' %word
            Wordlist.write(str(word).upper())
            Wordlist.write(str(word).lower())
            Wordlist.write(str(word).title())
            Bank.append(str(word).lower())




if __name__=='__main__':        
    Main();
    Generate(wordlist,Name)
    system('clear');exit('[-] Done')

2 个答案:

答案 0 :(得分:1)

为每个单词调用clear会大大减慢您的程序速度。删除这些电话。你的程序是IO绑定的,所以加快它的速度,意味着加快写作速度。使用SSD。使用集而不是列表:

#!/usr/bin/env python
import os
import sys

def generate(lst, save):
    with open(lst, 'r') as words, open(save, 'a') as output:
        bank = set()
        for word in words:
            if 7 < len(word) - 1 <= 10 and word.lower() not in bank:
                print '[+] Modding: %s' % word
                output.write(word.upper())
                output.write(word.lower())
                output.write(word.title())
                bank.append(word.lower())

def main():
    wordlist = raw_input("Enter The listfile Name: ")  
    if not path.exists(wordlist):
        return "'%s' Not Found" % wordlist

    name = raw_input("Enter Name To Save As: ") 
    if path.exists(Name):
        return "'%s' Already Exists" % name
    generate(wordlist, name)
    return '[-] Done'

if __name__=='__main__':        
    sys.exit(main())

答案 1 :(得分:0)

您正在尝试做的事情,制作一个词汇表的排列非常昂贵。

然而,2个提示:

小心系统

系统,就像在C中一样,有很多开销。在内环中,它被调用很多次。这会严重减慢它。

for word in words:
        if int(len(str(word))-1) > 7 and int(len(str(word))-1) <= 10 and str(word).lower() not in Bank:
            system('clear')
            ...

的Python

CPython并不是那么快,像numba这样的图书馆和像Pypy这样的翻译人员确实在很大程度上改善了这一点。但是,如果您想制作尽可能快的东西,请转到C.