필자는 Python을 처음 접했을 때 fastq 파일에서 임의로 시퀀스의 하위 집합을 선택한다고 가정합니다 (아마도 매우 못생긴) 스크립트를 작성했습니다. fastq-file은 정보를 4 행씩 블록 단위로 저장합니다. 각 블록의 첫 번째 행은 문자 "@"로 시작합니다. 입력 파일로 사용하는 fastq 파일은 약 14,000,000 줄을 포함하는 36GB입니다.파이썬 스크립트를 더 빠르게 만들 수 있습니까?
너무 많은 메모리를 사용하는 기존 스크립트를 다시 작성하려고 시도했으며 메모리 사용량을 많이 줄였습니다. 그러나 스크립트는 영원히 돌아가며 왜 나타나는지를 보지 못합니다.
parser = argparse.ArgumentParser()
parser.add_argument("infile", type = str, help = "The name of the fastq input file.", default = sys.stdin)
parser.add_argument("outputfile", type = str, help = "Name of the output file.")
parser.add_argument("-n", help="Number of sequences to sample", default=1)
args = parser.parse_args()
def sample():
linesamples = []
infile = open(args.infile, 'r')
outputfile = open(args.outputfile, 'w')
# count the number of fastq "chunks" in the input file:
seqs = subprocess.check_output(["grep", "-c", "@", str(args.infile)])
# randomly select n fastq "chunks":
seqsamples = random.sample(xrange(0,int(seqs)), int(args.n))
# make a list of the lines that are to be fetched from the fastq file:
for i in seqsamples:
linesamples.append(int(4*i+0))
linesamples.append(int(4*i+1))
linesamples.append(int(4*i+2))
linesamples.append(int(4*i+3))
# fetch lines from input file and write them to output file.
for i, line in enumerate(infile):
if i in linesamples:
outputfile.write(line)
위한 grep 단계는 전혀 실제적으로 더 시간이 필요 없지만, 500 분, 스크립트는 여전히 출력 파일에 쓰기 시작되지 않았습니다. 그래서 grep과 마지막 for-loop 사이의 단계 중 하나라고 생각합니다. 하지만 정확히 어떤 단계인지 이해하지 못하고 속도를 높이기 위해 할 수있는 일이 있습니다.
어떤 단계가 멈추는 지 확인하려면 [profiling] (https://docs.python.org/2/library/profile.html) 프로그램을 고려해야합니다.또한 작은 파일에서 코드를 실행 해 보았고 실행이 완료되었는지 확인 했습니까? 나중에 최적화 할 때 고려해야 할 또 하나의 단계는 스레딩과 다중 처리를 사용하여 작업을 분류하는 것입니다. –
루프 내에서 항상'int'를 호출하지 마십시오. 또한,'with' 문을 사용하십시오. – Veedrac