gpt4 book ai didi

python - 如何使我的 Python 脚本更快?

转载 作者:太空狗 更新时间:2023-10-29 21:55:02 24 4
gpt4 key购买 nike

我是 Python 的新手,我编写了一个(可能非常丑陋的)脚本,该脚本应该从 fastq 文件中随机选择一个序列子集。 fastq 文件将信息存储在每 block 四行的 block 中。每个 block 中的第一行以字符“@”开头。我用作输入文件的 fastq 文件是 36 GB,包含大约 14,000,000 行。

我试图重写一个已经存在的脚本,它使用了太多内存,并且我成功地减少了内存使用量。但是脚本需要很长时间才能运行,我不明白为什么。

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 循环之间花费这么长时间的步骤之一。但我不明白具体是哪一步,以及我可以做些什么来加快速度。

最佳答案

根据 linesamples 的大小,if i in linesamples 将花费很长时间,因为您要通过 infile< 搜索每个迭代的列表。您可以将其转换为 set 以缩短查找时间。此外,enumerate 效率不高 - 我已将其替换为我们在每次迭代中递增的 line_num 结构。

def sample():
linesamples = set()
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))
for i in seqsamples:
linesamples.add(int(4*i+0))
linesamples.add(int(4*i+1))
linesamples.add(int(4*i+2))
linesamples.add(int(4*i+3))
# make a list of the lines that are to be fetched from the fastq file:
# fetch lines from input file and write them to output file.
line_num = 0
for line in infile:
if line_num in linesamples:
outputfile.write(line)
line_num += 1
outputfile.close()

关于python - 如何使我的 Python 脚本更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27304959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com