Python多处理没有使用完整的cpu内核

2024-04-24 00:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用regex检查一个成对的fastq文件的序列记录,并将匹配的序列写入相同的文件中。我使用多处理来加速它,但是当我用20个进程运行它时,20个cpu核心都使用了2%,总时间与在单个核心中运行的时间相同。这是否意味着regex搜索比将输出写入文件更快,因此进程正在等待?你能建议我如何改进多重处理吗?附件是代码。你知道吗


def mycallback(x):
    SeqIO.write(x[0],outfile1,result.form)
    SeqIO.write(x[1],outfile2,result.form)
    SeqIO.write(x[2],outfile3,result.form)
    SeqIO.write(x[3],outfile4,result.form)

def check(x):
    if regex.search(r'^.{0,20}(?:'+fp+'){e<='+str(result.mm)+'}',str(x[0].seq),flags=regex.I) and regex.search(r'^.{0,20}(?:'+rp+'){e<='+str(result.mm)+'}',str(x[1].seq),flags=regex.I):
    return((x[0],x[1],'',''))
    elif regex.search(r'^.{0,20}(?:'+fp+'){e<='+str(result.mm)+'}',str(x[1].seq),flags=regex.I) and regex.search(r'^.{0,20}(?:'+rp+'){e<='+str(result.mm)+'}',str(x[0].seq),flags=regex.I):
    return((x[1],x[0],'',''))
    else:
    return(('','',x[0],x[1]))

p=Pool(int(result.n))
for i in izip(SeqIO.parse(result.fseq,result.form),SeqIO.parse(result.rseq,result.form)):
    p.apply_async(check,args=(i,),callback=mycallback)

p.close()
p.join()

Tags: 文件form核心searchreturn进程序列result
1条回答
网友
1楼 · 发布于 2024-04-24 00:27:30

Python的^{}实现在主进程内的线程内调用回调函数,并且受到GIL的限制。因此,您将按顺序等待所有文件写入。你知道吗

Callbacks should complete immediately since otherwise the thread which handles the results will get blocked.

我可以想象您的regex执行速度比文件写入快,因此您可以从将回调发送到自己的线程中获得最大的好处(这样就可以一次将多个文件写入排队)。Python线程应该在等待IO(文件写入)时释放GIL,并且比进程轻得多(启动速度更快)。你知道吗

相关问题 更多 >